Laravel 服务容器解析

来看一个简单的例子:

在这个例子中,控制器 需要从数据源中获取 users 。因此,我们要 注入 可以获取 users 的服务。在这种情况下,UserRepository 可能是使用 Eloquent 从数据库中获取 user 信息。因为 Repository 是通过 UserRepository 注入的,所以我们可以轻易地将其切换为另一个实现。这种注入方式的便利之处还体现在当我们为应用编写测试时,我们还可以轻松地「模拟」或创建 UserRepository 的虚拟实现。

想要构建强大的大型应用,至关重要的一件事是:要深刻的理解 Laravel 服务容器。当然,为 Laravel 的核心代码做出贡献也一样。

因为几乎所有服务容器绑定操作都是在 中注册的,所以文档中大多数例子都是使用了在服务提供器中绑定的容器。

简单绑定

在服务提供器中,你可以通过 $this->app 属性访问容器。我们可以通过 bind 方法注册绑定,传递我们想要注册的类或接口名称再返回类的实例的 Closure

  1. $this->app->bind('HelpSpot\API', function ($app) {
  2. return new HelpSpot\API($app->make('HttpClient'));
  3. });

注意,我们接受容器本身作为解析器的参数。然后,我们可以使用容器来解析正在构建的对象的子依赖。

绑定一个单例

singleton 方法将类或接口绑定到只能解析一次的容器中。绑定的单例被解析后,相同的对象实例会在随后的调用中返回到容器中:

  1. $this->app->singleton('HelpSpot\API', function ($app) {
  2. return new HelpSpot\API($app->make('HttpClient'));
  3. });

绑定实例

你也可以使用 instance 方法将现有对象实例绑定到容器中。给定的实例会始终在随后的调用中返回到容器中:

  1. $api = new HelpSpot\API(new HttpClient);
  2. $this->app->instance('HelpSpot\API', $api);

绑定初始数据

  1. $this->app->when('App\Http\Controllers\UserController')
  2. ->needs('$variableName')
  3. ->give($value);

服务容器有一个强大的功能,就是将接口绑定到给定实现。例如,如果我们有一个 EventPusher 接口和一个 RedisEventPusher 实现。编写完接口的 RedisEventPusher 实现后,我们就可以在服务容器中注册它,像这样:

这么做相当于告诉容器:当一个类需要实现 EventPusher 时,应该注入 RedisEventPusher。现在我们就可以在构造函数或者任何其他通过服务容器注入依赖项的地方使用类型提示注入 EventPusher 接口:

  1. use App\Contracts\EventPusher;
  2. /**
  3. * Create a new class instance.
  4. *
  5. * @param EventPusher $pusher
  6. * @return void
  7. */
  8. public function __construct(EventPusher $pusher)
  9. $this->pusher = $pusher;
  10. }

有时候,你可能有两个类使用了相同的接口,但你希望每个类都能注入不同的实现。例如,两个控制器可能需要依赖不同的 Illuminate\Contracts\Filesystem\Filesystem 契约 实现。 Laravel 提供了一个简单、优雅的接口来定义这个行为:

  1. use Illuminate\Support\Facades\Storage;
  2. use App\Http\Controllers\PhotoController;
  3. use Illuminate\Contracts\Filesystem\Filesystem;
  4. $this->app->when(PhotoController::class)
  5. ->needs(Filesystem::class)
  6. ->give(function () {
  7. return Storage::disk('local');
  8. });
  9. $this->app->when(VideoController::class)
  10. ->needs(Filesystem::class)
  11. ->give(function () {
  12. return Storage::disk('s3');
  13. });

有时候,你可能需要解析某个「分类」下的所有绑定。例如,你正在构建一个报表的聚合器,它接收一个包含不同 Report 接口实现的数组。注册了 Report 实现后,你可以使用 tag 方法为其分配标签:

  1. $this->app->bind('SpeedReport', function () {
  2. //
  3. });
  4. $this->app->bind('MemoryReport', function () {
  5. //
  6. });
  7. $this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');

服务被标记后,你可以通过 tagged 方法轻松地将它们全部解析:

  1. $this->app->bind('ReportAggregator', function ($app) {
  2. return new ReportAggregator($app->tagged('reports'));
  3. });

extend 方法可以修改解析的服务。例如,当一个服务被解析后,你可以添加额外的代码去修饰或配置这个服务。 extend 方法接受一个闭包,闭包的唯一参数和返回值都是一个服务:

make 方法

你可以使用 make 方法将容器中的类实例解析出来。make 方法接受要解析的类或接口的名称:

  1. $api = $this->app->make('HelpSpot\API');

如果你的代码处于不能访问 $app 变量的位置,你可以使用全局的辅助函数 resolve

  1. $api = resolve('HelpSpot\API');

如果你的某些类的依赖项不能通过容器去解析,那你可以通过将它们作为关联数组传递到 makeWith 方法来注入它们。

  1. $api = $this->app->makeWith('HelpSpot\API', ['id' => 1]);

自动注入

你可以简单地使用「类型提示」的方式在由容器解析的类的构造函数中添加依赖项,包括 、监听事件、、中间件 等。 事实上,这是你的大多数对象也应该由容器解析。

例如,你可以在控制器的构造函数中对应用程序定义的 Repository 使用类型提示。Repository 会被自动解析并注入到类中:

  1. <?php
  2. class UserController extends Controller
  3. {
  4. /**
  5. * UserRepository 的实例对象
  6. */
  7. protected $users;
  8. /**
  9. * 控制器的构造函数
  10. *
  11. * @param UserRepository $users
  12. * @return void
  13. */
  14. public function __construct(UserRepository $users)
  15. {
  16. $this->users = $users;
  17. }
  18. /**
  19. * 显示 ID 对应的用户
  20. *
  21. * @param int $id
  22. * @return Response
  23. */
  24. public function show($id)
  25. {
  26. //
  27. }
  28. }

每当服务容器解析一个对象时触发一个事件。你可以使用 resolving 方法监听这个事件:

如你所见,被解析的对象会被传递给回调中,让你在对象被传递出去之前可以在对象上设置任何属性。

Laravel 的服务容器实现了 接口。 因此,你可以使用 PSR-11容器『接口类型提示』来获取 Laravel 容器的实例:

  1. use Psr\Container\ContainerInterface;
  2. Route::get('/', function (ContainerInterface $container) {
  3. $service = $container->get('Service');
  4. //
  5. });

本文章首发在 LearnKu.com 网站上。