Skip to content
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待
虚位以待

服务容器

简介

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

让我们看一个简单的例子:

php
<?php

namespace App\Http\Controllers;

use App\Services\AppleMusic;
use Illuminate\View\View;

class PodcastController extends Controller
{
    /**
     * 创建一个新的控制器实例。
     */
    public function __construct(
        protected AppleMusic $apple,
    ) {}

    /**
     * 显示指定播客的信息。
     */
    public function show(string $id): View
    {
        return view('podcasts.show', [
            'podcast' => $this->apple->findPodcast($id)
        ]);
    }
}

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

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

零配置解析

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

php
<?php

class Service
{
    // ...
}

Route::get('/', function (Service $service) {
    dd($service::class);
});

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

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

何时使用容器

得益于零配置解析,你通常可以在路由、控制器、事件监听器等地方类型提示依赖项,而无需手动与容器交互。例如,你可以在路由定义中类型提示 Illuminate\Http\Request 对象,以便轻松访问当前请求。尽管我们无需编写与容器交互的代码就能实现这一点,但容器在幕后管理着这些依赖项的注入:

php
use Illuminate\Http\Request;

Route::get('/', function (Request $request) {
    // ...
});

在许多情况下,由于自动依赖注入和门面,你可以在从不手动绑定或解析容器中任何内容的情况下构建 Laravel 应用程序。那么,你什么时候会需要手动与容器交互呢? 让我们探讨两种情况。

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

绑定

绑定基础

简单绑定

几乎所有的服务容器绑定都会在服务提供者中注册,因此大多数示例将在此上下文中演示容器的使用。

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

php
use App\Services\Transistor;
use App\Services\PodcastParser;
use Illuminate\Contracts\Foundation\Application;

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

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

如前所述,你通常会在服务提供者中与容器交互;但是,如果你想在服务提供者之外与容器交互,可以通过 App 门面 进行:

php
use App\Services\Transistor;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\App;

App::bind(Transistor::class, function (Application $app) {
    // ...
});

你可以使用 bindIf 方法仅在尚未为给定类型注册绑定时注册容器绑定:

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

为了方便,你可以省略将类或接口名称作为单独参数提供,而是让 Laravel 从提供给 bind 方法的闭包的返回类型中推断类型:

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

NOTE

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

绑定单例

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

php
use App\Services\Transistor;
use App\Services\PodcastParser;
use Illuminate\Contracts\Foundation\Application;

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

你可以使用 singletonIf 方法仅在尚未为给定类型注册绑定时注册单例容器绑定:

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

Singleton 属性

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

php
<?php

namespace App\Services;

use Illuminate\Container\Attributes\Singleton;

#[Singleton]
class Transistor
{
    // ...
}

绑定作用域单例

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

php
use App\Services\Transistor;
use App\Services\PodcastParser;
use Illuminate\Contracts\Foundation\Application;

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

你可以使用 scopedIf 方法仅在尚未为给定类型注册绑定时注册作用域容器绑定:

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

Scoped 属性

或者,你可以使用 #[Scoped] 属性标记接口或类,以向容器指示它应在给定的 Laravel 请求/作业生命周期内仅解析一次:

php
<?php

namespace App\Services;

use Illuminate\Container\Attributes\Scoped;

#[Scoped]
class Transistor
{
    // ...
}

绑定实例

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

php
use App\Services\Transistor;
use App\Services\PodcastParser;

$service = new Transistor(new PodcastParser);

$this->app->instance(Transistor::class, $service);

绑定接口到实现

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

php
use App\Contracts\EventPusher;
use App\Services\RedisEventPusher;

$this->app->bind(EventPusher::class, RedisEventPusher::class);

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

php
use App\Contracts\EventPusher;

/**
 * 创建一个新的类实例。
 */
public function __construct(
    protected EventPusher $pusher,
) {}

Bind 属性

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

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

php
<?php

namespace App\Contracts;

use App\Services\FakeEventPusher;
use App\Services\RedisEventPusher;
use Illuminate\Container\Attributes\Bind;

#[Bind(RedisEventPusher::class)]
#[Bind(FakeEventPusher::class, environments: ['local', 'testing'])]
interface EventPusher
{
    // ...
}

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

php
use App\Services\RedisEventPusher;
use Illuminate\Container\Attributes\Bind;
use Illuminate\Container\Attributes\Singleton;

#[Bind(RedisEventPusher::class)]
#[Singleton]
interface EventPusher
{
    // ...
}

上下文绑定

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

php
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\UploadController;
use App\Http\Controllers\VideoController;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;

$this->app->when(PhotoController::class)
    ->needs(Filesystem::class)
    ->give(function () {
        return Storage::disk('local');
    });

$this->app->when([VideoController::class, UploadController::class])
    ->needs(Filesystem::class)
    ->give(function () {
        return Storage::disk('s3');
    });

上下文属性

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

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

php
<?php

namespace App\Http\Controllers;

use Illuminate\Container\Attributes\Storage;
use Illuminate\Contracts\Filesystem\Filesystem;

class PhotoController extends Controller
{
    public function __construct(
        #[Storage('local')] protected Filesystem $filesystem
    ) {
        // ...
    }
}

除了 Storage 属性,Laravel 还提供了 AuthCacheConfigContextDBGiveLogRouteParameterTag 属性:

php
<?php

namespace App\Http\Controllers;

use App\Contracts\UserRepository;
use App\Models\Photo;
use App\Repositories\DatabaseRepository;
use Illuminate\Container\Attributes\Auth;
use Illuminate\Container\Attributes\Cache;
use Illuminate\Container\Attributes\Config;
use Illuminate\Container\Attributes\Context;
use Illuminate\Container\Attributes\DB;
use Illuminate\Container\Attributes\Give;
use Illuminate\Container\Attributes\Log;
use Illuminate\Container\Attributes\RouteParameter;
use Illuminate\Container\Attributes\Tag;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Database\Connection;
use Psr\Log\LoggerInterface;

class PhotoController extends Controller
{
    public function __construct(
        #[Auth('web')] protected Guard $auth,
        #[Cache('redis')] protected Repository $cache,
        #[Config('app.timezone')] protected string $timezone,
        #[Context('uuid')] protected string $uuid,
        #[Context('ulid', hidden: true)] protected string $ulid,
        #[DB('mysql')] protected Connection $connection,
        #[Give(DatabaseRepository::class)] protected UserRepository $users,
        #[Log('daily')] protected LoggerInterface $log,
        #[RouteParameter('photo')] protected Photo $photo,
        #[Tag('reports')] protected iterable $reports,
    ) {
        // ...
    }
}

此外,Laravel 还提供了一个 CurrentUser 属性,用于将当前经过身份验证的用户注入到给定路由或类中:

php
use App\Models\User;
use Illuminate\Container\Attributes\CurrentUser;

Route::get('/user', function (#[CurrentUser] User $user) {
    return $user;
})->middleware('auth');

定义自定义属性

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

php
<?php

namespace App\Attributes;

use Attribute;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Container\ContextualAttribute;

#[Attribute(Attribute::TARGET_PARAMETER)]
class Config implements ContextualAttribute
{
    /**
     * 创建一个新的属性实例。
     */
    public function __construct(public string $key, public mixed $default = null)
    {
    }

    /**
     * 解析配置值。
     *
     * @param  self  $attribute
     * @param  \Illuminate\Contracts\Container\Container  $container
     * @return mixed
     */
    public static function resolve(self $attribute, Container $container)
    {
        return $container->make('config')->get($attribute->key, $attribute->default);
    }
}

绑定基本值

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

php
use App\Http\Controllers\UserController;

$this->app->when(UserController::class)
    ->needs('$variableName')
    ->give($value);

有时一个类可能依赖于一个标记实例的数组。使用 giveTagged 方法,你可以轻松地注入具有该标记的所有容器绑定:

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

如果你需要从应用程序的配置文件中注入一个值,可以使用 giveConfig 方法:

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

绑定类型可变参数

有时,你可能有一个类使用可变参数构造函数参数接收类型化对象的数组:

php
<?php

use App\Models\Filter;
use App\Services\Logger;

class Firewall
{
    /**
     * 过滤器实例。
     *
     * @var array
     */
    protected $filters;

    /**
     * 创建一个新的类实例。
     */
    public function __construct(
        protected Logger $logger,
        Filter ...$filters,
    ) {
        $this->filters = $filters;
    }
}

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

php
$this->app->when(Firewall::class)
    ->needs(Filter::class)
    ->give(function (Application $app) {
          return [
              $app->make(NullFilter::class),
              $app->make(ProfanityFilter::class),
              $app->make(TooLongFilter::class),
          ];
    });

为了方便,你也可以仅提供一个类名数组,由容器在 Firewall 需要 Filter 实例时解析:

php
$this->app->when(Firewall::class)
    ->needs(Filter::class)
    ->give([
        NullFilter::class,
        ProfanityFilter::class,
        TooLongFilter::class,
    ]);

可变参数标记依赖

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

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

标记

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

php
$this->app->bind(CpuReport::class, function () {
    // ...
});

$this->app->bind(MemoryReport::class, function () {
    // ...
});

$this->app->tag([CpuReport::class, MemoryReport::class], 'reports');

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

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

扩展绑定

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

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

解析

make 方法

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

php
use App\Services\Transistor;

$transistor = $this->app->make(Transistor::class);

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

php
use App\Services\Transistor;

$transistor = $this->app->makeWith(Transistor::class, ['id' => 1]);

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

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

如果你在服务提供者之外的代码位置,无法访问 $app 变量,你可以使用 App 门面app 辅助函数从容器中解析类实例:

php
use App\Services\Transistor;
use Illuminate\Support\Facades\App;

$transistor = App::make(Transistor::class);

$transistor = app(Transistor::class);

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

php
use Illuminate\Container\Container;

/**
 * 创建一个新的类实例。
 */
public function __construct(
    protected Container $container,
) {}

自动注入

另外,重要的是,你可以在由容器解析的类的构造函数中类型提示依赖项,包括控制器事件监听器中间件等。此外,你可以在队列任务handle 方法中类型提示依赖项。在实践中,这是大多数对象由容器解析的方式。

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

php
<?php

namespace App\Http\Controllers;

use App\Services\AppleMusic;

class PodcastController extends Controller
{
    /**
     * 创建一个新的控制器实例。
     */
    public function __construct(
        protected AppleMusic $apple,
    ) {}

    /**
     * 显示指定播客的信息。
     */
    public function show(string $id): Podcast
    {
        return $this->apple->findPodcast($id);
    }
}

方法调用与注入

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

php
<?php

namespace App;

use App\Services\AppleMusic;

class PodcastStats
{
    /**
     * 生成一个新的播客统计报告。
     */
    public function generate(AppleMusic $apple): array
    {
        return [
            // ...
        ];
    }
}

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

php
use App\PodcastStats;
use Illuminate\Support\Facades\App;

$stats = App::call([new PodcastStats, 'generate']);

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

php
use App\Services\AppleMusic;
use Illuminate\Support\Facades\App;

$result = App::call(function (AppleMusic $apple) {
    // ...
});

容器事件

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

php
use App\Services\Transistor;
use Illuminate\Contracts\Foundation\Application;

$this->app->resolving(Transistor::class, function (Transistor $transistor, Application $app) {
    // 当容器解析类型为 "Transistor" 的对象时调用...
});

$this->app->resolving(function (mixed $object, Application $app) {
    // 当容器解析任何类型的对象时调用...
});

如你所见,正在被解析的对象将被传递给回调,允许你在将其交给消费者之前在该对象上设置任何其他属性。

重新绑定

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

php
use App\Contracts\PodcastPublisher;
use App\Services\SpotifyPublisher;
use App\Services\TransistorPublisher;
use Illuminate\Contracts\Foundation\Application;

$this->app->bind(PodcastPublisher::class, SpotifyPublisher::class);

$this->app->rebinding(
    PodcastPublisher::class,
    function (Application $app, PodcastPublisher $newInstance) {
        //
    },
);

// 新的绑定将触发重新绑定闭包...
$this->app->bind(PodcastPublisher::class, TransistorPublisher::class);

PSR-11

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

php
use App\Services\Transistor;
use Psr\Container\ContainerInterface;

Route::get('/', function (ContainerInterface $container) {
    $service = $container->get(Transistor::class);

    // ...
});

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