服务容器
服务容器
绑定
几乎所有的服务容器绑定都会注册至 服务提供者 中,所以下方所有的例子将示范在该情境中使用容器。不过,如果它们没有依赖任何的接口,那么就没有将类绑定至容器中的必要。并不需要为容器指定如何建构这些对象,因为它会通过 PHP 的反射服务自动解析「实际」的对象。
在服务提供者中,你总是可以通过 $this->app
实例变量访问容器。我们可以使用 bind
方法注册一个绑定,传递我们希望注册的类或接口名称,并连同返回该类实例的闭包
:
$this->app->bind('HelpSpot\API', function ($app) {
return new HelpSpot\API($app['HttpClient']);
});
注意,我们获取到的容器本身作为参数传递给解析器。我们可以使用容器来解析我们绑定对象的次要依赖。
绑定一个单例
singletion
方法绑定一个只会被解析一次的类或接口至容器中,且后面的调用都会从容器中返回相同的实例:
$this->app->singleton('FooBar', function ($app) {
return new FooBar($app['SomethingElse']);
});
绑定实例
你也可以使用 instance
方法,绑定一个已经存在的对象实例至容器中。后面的调用都会从容器中返回指定的实例:
$fooBar = new FooBar(new SomethingElse);
$this->app->instance('FooBar', $fooBar);
绑定接口至实现
服务容器有个非常强大的特色功能,就是能够将指定的实现绑定至接口。举个例子,让我们假设我们有个 EventPusher
接口及一个 RedisEventPusher
实现。一旦我们编写完该接口的 RedisEventPusher
实现,就可以将它注册至服务容器:
$this->app->bind('App\Contracts\EventPusher', 'App\Services\RedisEventPusher');
这么做会告知容器当有个类需要 EventPusher
的实现时,必须注入 RedisEventPusher
。现在我们可以在构造器中对 EventPusher
接口使用类型提示,或任何需要通过服务容器注入依赖的其它位置:
use App\Contracts\EventPusher;
/**
* Create a new class instance.
*
* @param EventPusher $pusher
* @return void
*/
public function __construct(EventPusher $pusher)
{
$this->pusher = $pusher;
}