gonzalo123 / injector
InjectorServiceProvider
1.0
2015-09-20 11:25 UTC
Requires
- silex/silex: ^1.3
This package is not auto-updated.
Last update: 2024-09-24 03:18:19 UTC
README
Silex 中定义服务提供者的另一种方法
假设我们有一个这个 Math 类
namespace Foo class Math { public function sum($i, $j) { return $i+$j; } }
并且我们想在 Silex 应用程序中使用它
include __DIR__ . "/../vendor/autoload.php"; use Silex\Application; use Foo\Math; $app = new Application(['debug' => true]); $app['math'] = function () { return new Math(); }; $app->get("/", function () use ($app) { return $app['math']->sum(1, 2); }); $app->run();
我们在 $app['math'] 中有一个 Service,但是,这个类的类型是什么?我们需要检查 Math 类以确定可用的公共函数。有时我有点懒,所以为了这个,我开发了这个小服务提供者,允许我们以不同的方法来定义我们的服务提供者。
include __DIR__ . "/../vendor/autoload.php"; use Silex\Application; use Injector\InjectorServiceProvider; use Foo\Math; $app = new Application(['debug' => true]); $app->register(new InjectorServiceProvider([ 'Foo\Math' => 'math', ])); $app['math'] = function () { return new Math(); }; $app->get("/", function (Math $math) { return $math->sum(1, 2); }); $app->run();
这就是全部。我们的 InjectorServiceProvider 允许我们在依赖注入容器中定义服务提供者提供的类及其 Silex/Pimple 键名。