服务容器

绑定/注册

#被注册至容器的闭包解析器包含一个 key (通常用类名称) 和一个有返回值的闭包:
$this->app->bind('FooBar', function(){})

#有时候,你可能希望绑定到容器的对象只会被解析一次,之后的调用都返回相同的实
$this->app->singleton('FooBar', function(){})

#你也可以使用 instance 方法,绑定一个已经存在的实例到容器,接下来将总是返回该实例
$this->instance('FooBar', $fooBar)

解析

$fooBar = $this->app->make('FooBar');
$fooBar = $this->app['FooBar'];

将接口绑定到实现

原文地址: http://www.golaravel.com/laravel/docs/5.0/container/#binding-interfaces-to-implementations

  //App\Contracts\EventPusher为接口,App\Services\PusherEventPusher为实现此接口的类
  $this->app->bind('App\Contracts\EventPusher', 'App\Services\PusherEventPusher');

上下文绑定

有时候,你可能会有两个类需要用到同一个接口,但是你希望为每个类注入不同的接口实现。 例如当我们的系统收到一个新的订单时,我们需要使用 PubNub 来代替 Pusher 发送消息。 Laravel 提供了一个简单便利的接口来定义以上的行为:

  $app->when('App\Handlers\Commands\CreateOrderHandler')
      ->needs('App\Contracts\EventPusher')
      ->give('App\Services\PubNubEventPusher');

容器事件

注册一个解析事件监听器
容器在解析每一个对象时就会触发一个事件。你可以用 resolving 方法来监听此事件:

$this->app->resolving(function($object, $app)
{
    // 当容器解析任意类型的依赖时被调用
});

$this->app->resolving(function(FooBar $fooBar, $app)
{
    // 当容器解析 `FooBar` 类型的依赖时被调用
});

被解析的对象将被传入到闭包方法中。

服务提供者