[Laravel]唠唠Service Container
什么是Service Container
从Laravel官方文档对于Service Container的解释可以看出,它的作用就是帮助我们管理和进行依赖注入的。 为什么要用Service Container在《唠唠依赖注入》中,我们看到使用依赖注入可以极大的降低代码的耦合度,但是也带来了一个缺点,就是需要自己管理注入的对象。 // public/index.php <?php require __DIR__.'/../bootstrap/autoload.php'; $app = require_once __DIR__.'/../bootstrap/app.php'; $kernel = $app->make(IlluminateContractsHttpKernel::class); $response = $kernel->handle( $request = IlluminateHttpRequest::capture() ); $response->send(); $kernel->terminate($request,$response); // bootstrap/app.php <?php $app = new IlluminateFoundationApplication( realpath(__DIR__.'/../') ); $app->singleton( IlluminateContractsHttpKernel::class,AppHttpKernel::class ); $app->singleton( IlluminateContractsConsoleKernel::class,AppConsoleKernel::class ); $app->singleton( IlluminateContractsDebugExceptionHandler::class,AppExceptionsHandler::class ); return $app; 首先看 是不是很简洁? 其实不单是Laravel,像Yii2、Phalcon等框架都通过实现容器来管理依赖注入。 如何使用Service Container既然是一个容器,无非就是两个事,往里放东西和往外取东西,对应到Service Container就是绑定(Binding)和解析(Resolving)。 获得容器在Laravel的Service Provider中,可以通过 以下都用$container代表获取到的容器。 绑定
//使用闭包 $container->bind('BarInterface',function(){ return new Bar(); }); //或者使用字符串 $container->bind('FooInterface','Foo');
$container->singleton('BarInterface',function(){ return new Bar(); });
$bar = new Bar(); $bar->setSomething(new Something); $container->instance('Bar',$bar);
$container->when('Man') ->needs('PartnerInterface') ->give('Woman'); $container->when('Woman') ->needs('PartnerInterface') ->give('Man');
$container->bind('Father',function () { // }); $container->bind('Mother',function () { // }); $container->bind('Daughter',function () { // }); $container->bind('Son',function () { // }); $container->tag(['Father','Mother','Daughter','Son'],'familyMembers'); $container->bind('Family',function ($container) { return new Family($container->tagged('familyMembers')); }); 解析
$foo = $container->make('Foo');
$bar = $container['Bar'];
$familyMembers = $container->tagged('familyMembers'); foreach ($familyMembers as $individual) { $individual->doSomething(); } 解析事件
$container->resolving(function ($object,$container) { // 当容器解析任何类型的对象时会被调用... }); $container->resolving('Foo',function (Foo $foo,$container) { // 当容器解析「Foo」类型的对象时会被调用... });
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |