跳转至内容

服务容器

简介

Laravel 服务容器是一个功能强大的工具,用于管理类依赖并执行依赖注入。依赖注入是一个花哨的术语,本质上意味着:类的依赖通过构造函数或在某些情况下通过“setter”方法被“注入”到类中。

让我们看一个简单的例子

1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Services\AppleMusic;
6use Illuminate\View\View;
7 
8class PodcastController extends Controller
9{
10 /**
11 * Create a new controller instance.
12 */
13 public function __construct(
14 protected AppleMusic $apple,
15 ) {}
16 
17 /**
18 * Show information about the given podcast.
19 */
20 public function show(string $id): View
21 {
22 return view('podcasts.show', [
23 'podcast' => $this->apple->findPodcast($id)
24 ]);
25 }
26}

在这个例子中,PodcastController 需要从数据源(如 Apple Music)检索播客。因此,我们将注入一个能够检索播客的服务。由于服务是注入的,我们在测试应用程序时可以轻松地“模拟”(mock)或创建一个 AppleMusic 服务的虚拟实现。

深入了解 Laravel 服务容器对于构建强大的大型应用程序以及为 Laravel 核心本身做出贡献至关重要。

零配置解析

如果一个类没有依赖项,或者仅依赖于其他具体类(而非接口),则无需指示容器如何解析该类。例如,您可以将以下代码放在 routes/web.php 文件中

1<?php
2 
3class Service
4{
5 // ...
6}
7 
8Route::get('/', function (Service $service) {
9 dd($service::class);
10});

在这个例子中,访问应用程序的 / 路由将自动解析 Service 类并将其注入到路由处理程序中。这具有改变游戏规则的意义。这意味着您可以开发应用程序并利用依赖注入,而无需担心臃肿的配置文件。

值得庆幸的是,在构建 Laravel 应用程序时,您编写的许多类都会通过容器自动接收它们的依赖项,包括 控制器事件监听器中间件等。此外,您还可以在 队列任务handle 方法中对依赖项进行类型提示。一旦您体验到自动且零配置依赖注入的强大功能,就会发现没有它几乎无法进行开发。

何时使用容器

得益于零配置解析,您通常可以在路由、控制器、事件监听器和其他地方对依赖项进行类型提示,而无需手动与容器交互。例如,您可以在路由定义上对 Illuminate\Http\Request 对象进行类型提示,以便轻松访问当前请求。即使我们从未为了编写此代码而与容器交互,它也在幕后管理着这些依赖项的注入。

1use Illuminate\Http\Request;
2 
3Route::get('/', function (Request $request) {
4 // ...
5});

在许多情况下,得益于自动依赖注入和 Facades,您可以构建 Laravel 应用程序而无需手动绑定或从容器中解析任何内容。那么,您何时需要手动与容器交互呢? 让我们探讨两种情况。

首先,如果您编写的类实现了接口,并且希望在路由或类构造函数中对该接口进行类型提示,则必须 告诉容器如何解析该接口。其次,如果您正在 编写一个 Laravel 包 并计划与其他 Laravel 开发者共享,则可能需要将包的服务绑定到容器中。

绑定

绑定基础

简单绑定

几乎所有的服务容器绑定都将在 服务提供者 中注册,因此大多数这些示例将演示如何在那种上下文中利用容器。

在服务提供者内部,您始终可以通过 $this->app 属性访问容器。我们可以使用 bind 方法注册绑定,传入我们希望注册的类或接口名称,以及一个返回该类实例的闭包。

1use App\Services\Transistor;
2use App\Services\PodcastParser;
3use Illuminate\Contracts\Foundation\Application;
4 
5$this->app->bind(Transistor::class, function (Application $app) {
6 return new Transistor($app->make(PodcastParser::class));
7});

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

如前所述,您通常会在服务提供者中与容器交互;但是,如果您想在服务提供者之外与容器交互,可以通过 App Facade 来实现。

1use App\Services\Transistor;
2use Illuminate\Contracts\Foundation\Application;
3use Illuminate\Support\Facades\App;
4 
5App::bind(Transistor::class, function (Application $app) {
6 // ...
7});

您可以使用 bindIf 方法仅在给定类型尚未注册绑定时才注册容器绑定。

1$this->app->bindIf(Transistor::class, function (Application $app) {
2 return new Transistor($app->make(PodcastParser::class));
3});

为了方便起见,您可以省略提供您希望注册的类或接口名称作为单独参数,而是让 Laravel 从您提供给 bind 方法的闭包的返回类型中推断类型。

1App::bind(function (Application $app): Transistor {
2 return new Transistor($app->make(PodcastParser::class));
3});

如果类不依赖任何接口,则无需将其绑定到容器中。容器无需被告知如何构建这些对象,因为它可以使用反射自动解析它们。

绑定单例

singleton 方法将类或接口绑定到容器中,该类或接口应仅被解析一次。一旦单例绑定被解析,后续对容器的调用将返回相同的对象实例。

1use App\Services\Transistor;
2use App\Services\PodcastParser;
3use Illuminate\Contracts\Foundation\Application;
4 
5$this->app->singleton(Transistor::class, function (Application $app) {
6 return new Transistor($app->make(PodcastParser::class));
7});

您可以使用 singletonIf 方法仅在给定类型尚未注册绑定时才注册单例容器绑定。

1$this->app->singletonIf(Transistor::class, function (Application $app) {
2 return new Transistor($app->make(PodcastParser::class));
3});

Singleton 属性

或者,您可以使用 #[Singleton] 属性标记接口或类,以向容器指示它应该被解析一次。

1<?php
2 
3namespace App\Services;
4 
5use Illuminate\Container\Attributes\Singleton;
6 
7#[Singleton]
8class Transistor
9{
10 // ...
11}

绑定作用域单例

scoped 方法将类或接口绑定到容器中,该类或接口仅应在给定的 Laravel 请求/任务生命周期内被解析一次。虽然此方法与 singleton 方法类似,但使用 scoped 方法注册的实例将在 Laravel 应用程序启动新“生命周期”时被清除,例如当 Laravel Octane 工作进程处理新请求,或 Laravel 队列工作进程 处理新任务时。

1use App\Services\Transistor;
2use App\Services\PodcastParser;
3use Illuminate\Contracts\Foundation\Application;
4 
5$this->app->scoped(Transistor::class, function (Application $app) {
6 return new Transistor($app->make(PodcastParser::class));
7});

您可以使用 scopedIf 方法仅在给定类型尚未注册绑定时才注册作用域容器绑定。

1$this->app->scopedIf(Transistor::class, function (Application $app) {
2 return new Transistor($app->make(PodcastParser::class));
3});

Scoped 属性

或者,您可以使用 #[Scoped] 属性标记接口或类,以向容器指示它应该在给定的 Laravel 请求/任务生命周期内被解析一次。

1<?php
2 
3namespace App\Services;
4 
5use Illuminate\Container\Attributes\Scoped;
6 
7#[Scoped]
8class Transistor
9{
10 // ...
11}

绑定实例

您还可以使用 instance 方法将现有的对象实例绑定到容器中。后续对容器的调用将始终返回给定的实例。

1use App\Services\Transistor;
2use App\Services\PodcastParser;
3 
4$service = new Transistor(new PodcastParser);
5 
6$this->app->instance(Transistor::class, $service);

将接口绑定到实现

服务容器的一个非常强大的功能是它能够将接口绑定到给定的实现。例如,假设我们有一个 EventPusher 接口和一个 RedisEventPusher 实现。一旦我们编写了该接口的 RedisEventPusher 实现,就可以像这样在服务容器中注册它。

1use App\Contracts\EventPusher;
2use App\Services\RedisEventPusher;
3 
4$this->app->bind(EventPusher::class, RedisEventPusher::class);

此语句告诉容器,当类需要 EventPusher 的实现时,应该注入 RedisEventPusher。现在,我们可以在容器解析的类的构造函数中对 EventPusher 接口进行类型提示。请记住,Laravel 应用程序中的控制器、事件监听器、中间件和其他各种类型的类始终使用容器进行解析。

1use App\Contracts\EventPusher;
2 
3/**
4 * Create a new class instance.
5 */
6public function __construct(
7 protected EventPusher $pusher,
8) {}

Bind 属性

为了更加方便,Laravel 还提供了 Bind 属性。您可以将此属性应用于任何接口,以告知 Laravel 每当请求该接口时应自动注入哪个实现。使用 Bind 属性时,无需在应用程序的服务提供者中执行任何额外的服务注册。

此外,可以在接口上放置多个 Bind 属性,以便为特定的环境集配置应注入的不同实现。

1<?php
2 
3namespace App\Contracts;
4 
5use App\Services\FakeEventPusher;
6use App\Services\RedisEventPusher;
7use Illuminate\Container\Attributes\Bind;
8 
9#[Bind(RedisEventPusher::class)]
10#[Bind(FakeEventPusher::class, environments: ['local', 'testing'])]
11interface EventPusher
12{
13 // ...
14}

此外,可以应用 SingletonScoped 属性来指示容器绑定是应该被解析一次还是每个请求/任务生命周期解析一次。

1use App\Services\RedisEventPusher;
2use Illuminate\Container\Attributes\Bind;
3use Illuminate\Container\Attributes\Singleton;
4 
5#[Bind(RedisEventPusher::class)]
6#[Singleton]
7interface EventPusher
8{
9 // ...
10}

上下文绑定

有时您可能有两个类使用相同的接口,但您希望向每个类注入不同的实现。例如,两个控制器可能依赖于 Illuminate\Contracts\Filesystem\Filesystem 契约 的不同实现。Laravel 提供了一个简单、流畅的接口来定义这种行为。

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

上下文属性

由于上下文绑定常用于注入驱动程序的实现或配置值,Laravel 提供了各种上下文绑定属性,允许注入这些类型的值,而无需在服务提供者中手动定义上下文绑定。

例如,Storage 属性可用于注入特定的 存储磁盘

1<?php
2 
3namespace App\Http\Controllers;
4 
5use Illuminate\Container\Attributes\Storage;
6use Illuminate\Contracts\Filesystem\Filesystem;
7 
8class PhotoController extends Controller
9{
10 public function __construct(
11 #[Storage('local')] protected Filesystem $filesystem
12 ) {
13 // ...
14 }
15}

除了 Storage 属性外,Laravel 还提供 AuthCacheConfigContextDBGiveLogRouteParameterTag 属性。

1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Contracts\UserRepository;
6use App\Models\Photo;
7use App\Repositories\DatabaseRepository;
8use Illuminate\Container\Attributes\Auth;
9use Illuminate\Container\Attributes\Cache;
10use Illuminate\Container\Attributes\Config;
11use Illuminate\Container\Attributes\Context;
12use Illuminate\Container\Attributes\DB;
13use Illuminate\Container\Attributes\Give;
14use Illuminate\Container\Attributes\Log;
15use Illuminate\Container\Attributes\RouteParameter;
16use Illuminate\Container\Attributes\Tag;
17use Illuminate\Contracts\Auth\Guard;
18use Illuminate\Contracts\Cache\Repository;
19use Illuminate\Database\Connection;
20use Psr\Log\LoggerInterface;
21 
22class PhotoController extends Controller
23{
24 public function __construct(
25 #[Auth('web')] protected Guard $auth,
26 #[Cache('redis')] protected Repository $cache,
27 #[Config('app.timezone')] protected string $timezone,
28 #[Context('uuid')] protected string $uuid,
29 #[Context('ulid', hidden: true)] protected string $ulid,
30 #[DB('mysql')] protected Connection $connection,
31 #[Give(DatabaseRepository::class)] protected UserRepository $users,
32 #[Log('daily')] protected LoggerInterface $log,
33 #[RouteParameter('photo')] protected Photo $photo,
34 #[Tag('reports')] protected iterable $reports,
35 ) {
36 // ...
37 }
38}

此外,Laravel 提供了一个 CurrentUser 属性,用于将当前已认证的用户注入到给定的路由或类中。

1use App\Models\User;
2use Illuminate\Container\Attributes\CurrentUser;
3 
4Route::get('/user', function (#[CurrentUser] User $user) {
5 return $user;
6})->middleware('auth');

定义自定义属性

您可以通过实现 Illuminate\Contracts\Container\ContextualAttribute 契约来创建自己的上下文属性。容器将调用您属性的 resolve 方法,该方法应解析应注入到使用该属性的类中的值。在下面的示例中,我们将重新实现 Laravel 内置的 Config 属性。

1<?php
2 
3namespace App\Attributes;
4 
5use Attribute;
6use Illuminate\Contracts\Container\Container;
7use Illuminate\Contracts\Container\ContextualAttribute;
8 
9#[Attribute(Attribute::TARGET_PARAMETER)]
10class Config implements ContextualAttribute
11{
12 /**
13 * Create a new attribute instance.
14 */
15 public function __construct(public string $key, public mixed $default = null)
16 {
17 }
18 
19 /**
20 * Resolve the configuration value.
21 *
22 * @param self $attribute
23 * @param \Illuminate\Contracts\Container\Container $container
24 * @return mixed
25 */
26 public static function resolve(self $attribute, Container $container)
27 {
28 return $container->make('config')->get($attribute->key, $attribute->default);
29 }
30}

绑定原始值

有时您可能有一个类接收一些注入的类,但也需要注入原始值,例如整数。您可以轻松地使用上下文绑定来注入类可能需要的任何值。

1use App\Http\Controllers\UserController;
2 
3$this->app->when(UserController::class)
4 ->needs('$variableName')
5 ->give($value);

有时一个类可能依赖于一组 带标签的 实例。使用 giveTagged 方法,您可以轻松注入所有带有该标签的容器绑定。

1$this->app->when(ReportAggregator::class)
2 ->needs('$reports')
3 ->giveTagged('reports');

如果您需要从应用程序的配置文件之一注入值,可以使用 giveConfig 方法。

1$this->app->when(ReportAggregator::class)
2 ->needs('$timezone')
3 ->giveConfig('app.timezone');

绑定类型化可变参数

有时,您可能会有一个类,它通过可变构造函数参数接收对象数组。

1<?php
2 
3use App\Models\Filter;
4use App\Services\Logger;
5 
6class Firewall
7{
8 /**
9 * The filter instances.
10 *
11 * @var array
12 */
13 protected $filters;
14 
15 /**
16 * Create a new class instance.
17 */
18 public function __construct(
19 protected Logger $logger,
20 Filter ...$filters,
21 ) {
22 $this->filters = $filters;
23 }
24}

使用上下文绑定,您可以通过为 give 方法提供一个返回已解析 Filter 实例数组的闭包来解析此依赖项。

1$this->app->when(Firewall::class)
2 ->needs(Filter::class)
3 ->give(function (Application $app) {
4 return [
5 $app->make(NullFilter::class),
6 $app->make(ProfanityFilter::class),
7 $app->make(TooLongFilter::class),
8 ];
9 });

为了方便起见,您也可以只提供一个类名数组,以便在 Firewall 需要 Filter 实例时由容器解析它们。

1$this->app->when(Firewall::class)
2 ->needs(Filter::class)
3 ->give([
4 NullFilter::class,
5 ProfanityFilter::class,
6 TooLongFilter::class,
7 ]);

可变标签依赖

有时一个类可能具有一个类型提示为给定类(Report ...$reports)的可变依赖项。使用 needsgiveTagged 方法,您可以轻松地为给定的依赖项注入所有带有该 标签 的容器绑定。

1$this->app->when(ReportAggregator::class)
2 ->needs(Report::class)
3 ->giveTagged('reports');

标签

有时您可能需要解析所有特定“类别”的绑定。例如,您可能正在构建一个报表分析器,它接收许多不同 Report 接口实现的数组。注册 Report 实现后,您可以使用 tag 方法为它们分配一个标签。

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

一旦服务被标记,您就可以通过容器的 tagged 方法轻松地解析它们。

1$this->app->bind(ReportAnalyzer::class, function (Application $app) {
2 return new ReportAnalyzer($app->tagged('reports'));
3});

扩展绑定

extend 方法允许修改已解析的服务。例如,当解析服务时,您可以运行额外的代码来装饰或配置该服务。extend 方法接受两个参数:您正在扩展的服务类,以及一个应该返回修改后服务的闭包。闭包接收正在解析的服务和容器实例。

1$this->app->extend(Service::class, function (Service $service, Application $app) {
2 return new DecoratedService($service);
3});

解析

make 方法

您可以使用 make 方法从容器中解析类实例。make 方法接受您希望解析的类或接口名称。

1use App\Services\Transistor;
2 
3$transistor = $this->app->make(Transistor::class);

如果您的类的某些依赖项无法通过容器解析,您可以通过将它们作为关联数组传递给 makeWith 方法来注入它们。例如,我们可以手动传递 Transistor 服务所需的 $id 构造函数参数。

1use App\Services\Transistor;
2 
3$transistor = $this->app->makeWith(Transistor::class, ['id' => 1]);

bound 方法可用于确定类或接口是否已在容器中显式绑定。

1if ($this->app->bound(Transistor::class)) {
2 // ...
3}

如果您处于服务提供者之外,且代码位置无法访问 $app 变量,则可以使用 App Facadeapp 辅助函数 从容器中解析类实例。

1use App\Services\Transistor;
2use Illuminate\Support\Facades\App;
3 
4$transistor = App::make(Transistor::class);
5 
6$transistor = app(Transistor::class);

如果您希望将 Laravel 容器实例本身注入到由容器解析的类中,则可以在类的构造函数中对 Illuminate\Container\Container 类进行类型提示。

1use Illuminate\Container\Container;
2 
3/**
4 * Create a new class instance.
5 */
6public function __construct(
7 protected Container $container,
8) {}

自动注入

或者,重要的是,您可以在由容器解析的类的构造函数中对依赖项进行类型提示,包括 控制器事件监听器中间件等。此外,您还可以在 队列任务handle 方法中对依赖项进行类型提示。实际上,这就是大多数对象应该由容器解析的方式。

例如,您可以在控制器的构造函数中对应用程序定义的服务进行类型提示。该服务将自动解析并注入到类中。

1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Services\AppleMusic;
6 
7class PodcastController extends Controller
8{
9 /**
10 * Create a new controller instance.
11 */
12 public function __construct(
13 protected AppleMusic $apple,
14 ) {}
15 
16 /**
17 * Show information about the given podcast.
18 */
19 public function show(string $id): Podcast
20 {
21 return $this->apple->findPodcast($id);
22 }
23}

方法调用与注入

有时您可能希望在对象实例上调用方法,同时允许容器自动注入该方法的依赖项。例如,给定以下类

1<?php
2 
3namespace App;
4 
5use App\Services\AppleMusic;
6 
7class PodcastStats
8{
9 /**
10 * Generate a new podcast stats report.
11 */
12 public function generate(AppleMusic $apple): array
13 {
14 return [
15 // ...
16 ];
17 }
18}

您可以像这样通过容器调用 generate 方法

1use App\PodcastStats;
2use Illuminate\Support\Facades\App;
3 
4$stats = App::call([new PodcastStats, 'generate']);

call 方法接受任何 PHP 可调用对象。容器的 call 方法甚至可以用于调用闭包,同时自动注入其依赖项。

1use App\Services\AppleMusic;
2use Illuminate\Support\Facades\App;
3 
4$result = App::call(function (AppleMusic $apple) {
5 // ...
6});

容器事件

服务容器在每次解析对象时都会触发一个事件。您可以使用 resolving 方法监听此事件。

1use App\Services\Transistor;
2use Illuminate\Contracts\Foundation\Application;
3 
4$this->app->resolving(Transistor::class, function (Transistor $transistor, Application $app) {
5 // Called when container resolves objects of type "Transistor"...
6});
7 
8$this->app->resolving(function (mixed $object, Application $app) {
9 // Called when container resolves object of any type...
10});

正如您所看到的,正在解析的对象将被传递给回调,允许您在对象交付给消费者之前对其设置任何附加属性。

重新绑定

rebinding 方法允许您在服务重新绑定到容器时进行监听,这意味着它在初始绑定后被再次注册或覆盖。当您需要在每次更新特定绑定时更新依赖项或修改行为时,这很有用。

1use App\Contracts\PodcastPublisher;
2use App\Services\SpotifyPublisher;
3use App\Services\TransistorPublisher;
4use Illuminate\Contracts\Foundation\Application;
5 
6$this->app->bind(PodcastPublisher::class, SpotifyPublisher::class);
7 
8$this->app->rebinding(
9 PodcastPublisher::class,
10 function (Application $app, PodcastPublisher $newInstance) {
11 //
12 },
13);
14 
15// New binding will trigger rebinding closure...
16$this->app->bind(PodcastPublisher::class, TransistorPublisher::class);

PSR-11

Laravel 的服务容器实现了 PSR-11 接口。因此,您可以对 PSR-11 容器接口进行类型提示,以获取 Laravel 容器的实例。

1use App\Services\Transistor;
2use Psr\Container\ContainerInterface;
3 
4Route::get('/', function (ContainerInterface $container) {
5 $service = $container->get(Transistor::class);
6 
7 // ...
8});

如果无法解析给定的标识符,则会抛出异常。如果标识符从未绑定,则该异常将是 Psr\Container\NotFoundExceptionInterface 的实例。如果标识符已绑定但无法解析,则将抛出 Psr\Container\ContainerExceptionInterface 的实例。