主题
Service Container
简介
Laravel service container 是一个用于管理类依赖和执行依赖注入的强大工具。依赖注入是一个花哨的术语,本质上意味着:类的依赖通过构造函数或在某些情况下通过 "setter" 方法"注入"到类中。
让我们看一个简单的例子:
php
<?php
namespace App\Http\Controllers;
use App\Services\AppleMusic;
use Illuminate\View\View;
class PodcastController extends Controller
{
/**
* Create a new controller instance.
*/
public function __construct(
protected AppleMusic $apple,
) {}
/**
* Show information about the given podcast.
*/
public function show(string $id): View
{
return view('podcasts.show', [
'podcast' => $this->apple->findPodcast($id)
]);
}
}在这个例子中,PodcastController 需要从数据源(如 Apple Music)检索播客。因此,我们将注入一个能够检索播客的服务。由于服务是注入的,我们可以在测试应用程序时轻松地 "mock" 或创建 AppleMusic 服务的虚拟实现。
深入理解 Laravel service container 对于构建强大的大型应用程序以及为 Laravel 核心做出贡献至关重要。
零配置解析
如果一个类没有依赖项或仅依赖于其他具体类(而非接口),则容器不需要被指示如何解析该类。例如,你可以在 routes/web.php 文件中放置以下代码:
php
<?php
class Service
{
// ...
}
Route::get('/', function (Service $service) {
dd($service::class);
});在这个例子中,访问应用程序的 / 路由将自动解析 Service 类并将其注入到路由处理程序中。这是革命性的。这意味着你可以开发应用程序并利用依赖注入,而无需担心臃肿的配置文件。
值得庆幸的是,在构建 Laravel 应用程序时,你编写的许多类都会通过容器自动接收其依赖项,包括控制器、事件监听器、middleware 等。此外,你还可以在队列任务的 handle 方法中类型提示依赖项。一旦你体验到自动和零配置依赖注入的强大功能,就会觉得没有它就无法开发。
何时使用容器
得益于零配置解析,你通常会在路由、控制器、事件监听器和其他地方类型提示依赖项,而无需手动与容器交互。例如,你可以在路由定义中类型提示 Illuminate\Http\Request 对象,以便轻松访问当前请求。尽管我们不需要与容器交互来编写此代码,但它在幕后管理着这些依赖项的注入:
php
use Illuminate\Http\Request;
Route::get('/', function (Request $request) {
// ...
});在许多情况下,得益于自动依赖注入和 facade,你可以构建 Laravel 应用程序而从不需要手动绑定或从容器解析任何内容。那么,你什么时候会手动与容器交互呢?让我们考察两种情况。
首先,如果你编写了一个实现接口的类,并且希望在路由或类构造函数中类型提示该接口,你必须告诉容器如何解析该接口。其次,如果你正在编写 Laravel 扩展包并计划与其他 Laravel 开发者共享,你可能需要将包的服务绑定到容器中。
绑定
绑定基础
简单绑定
几乎所有的 service container 绑定都将在 service provider 中注册,因此大多数示例将演示在该上下文中使用容器。
在 service provider 中,你始终可以通过 $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));
});注意,我们接收容器本身作为解析器的参数。然后我们可以使用容器来解析我们正在构建的对象的子依赖。
如前所述,你通常会在 service provider 中与容器交互;但是,如果你想在 service provider 之外与容器交互,可以通过 App facade 来实现:
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 worker 处理新请求时或 Laravel 队列 worker 处理新任务时:
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);将接口绑定到实现
Service container 的一个非常强大的功能是能够将接口绑定到给定的实现。例如,假设我们有一个 EventPusher 接口和一个 RedisEventPusher 实现。一旦我们编写了该接口的 RedisEventPusher 实现,就可以像这样将其注册到 service container 中:
php
use App\Contracts\EventPusher;
use App\Services\RedisEventPusher;
$this->app->bind(EventPusher::class, RedisEventPusher::class);此语句告诉容器,当类需要 EventPusher 的实现时,应该注入 RedisEventPusher。现在我们可以在由容器解析的类的构造函数中类型提示 EventPusher 接口。请记住,控制器、事件监听器、middleware 以及 Laravel 应用程序中的各种其他类型的类始终使用容器解析:
php
use App\Contracts\EventPusher;
/**
* Create a new class instance.
*/
public function __construct(
protected EventPusher $pusher,
) {}Bind 属性
Laravel 还提供了 Bind 属性以增加便利性。你可以将此属性应用于任何接口,以告诉 Laravel 每当请求该接口时应自动注入哪个实现。使用 Bind 属性时,无需在应用程序的 service provider 中执行任何额外的服务注册。
此外,可以在接口上放置多个 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
{
// ...
}此外,可以应用 Singleton 和 Scoped 属性来指示容器绑定应解析一次还是每个请求/任务生命周期解析一次:
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 contract 的不同实现。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 提供了各种上下文绑定属性,允许你无需在 service provider 中手动定义上下文绑定即可注入这些类型的值。
例如,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 还提供 Auth、Cache、Config、Context、DB、Give、Log、RouteParameter 和 Tag 属性:
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 contract 来创建自己的上下文属性。容器将调用你的属性的 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
{
/**
* Create a new attribute instance.
*/
public function __construct(public string $key, public mixed $default = null)
{
}
/**
* Resolve the configuration value.
*
* @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
{
/**
* The filter instances.
*
* @var array
*/
protected $filters;
/**
* Create a new class instance.
*/
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)。使用 needs 和 giveTagged 方法,你可以轻松注入具有该标签的所有容器绑定作为给定依赖:
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)) {
// ...
}如果你在 service provider 之外的代码位置无法访问 $app 变量,可以使用 App facade 或 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;
/**
* Create a new class instance.
*/
public function __construct(
protected Container $container,
) {}自动注入
另外,也是最重要的,你可以在由容器解析的类的构造函数中类型提示依赖项,包括控制器、事件监听器、middleware 等。此外,你还可以在队列任务的 handle 方法中类型提示依赖项。实际上,这是你的大多数对象应该由容器解析的方式。
例如,你可以在控制器的构造函数中类型提示由应用程序定义的服务。该服务将被自动解析并注入到类中:
php
<?php
namespace App\Http\Controllers;
use App\Services\AppleMusic;
class PodcastController extends Controller
{
/**
* Create a new controller instance.
*/
public function __construct(
protected AppleMusic $apple,
) {}
/**
* Show information about the given podcast.
*/
public function show(string $id): Podcast
{
return $this->apple->findPodcast($id);
}
}方法调用与注入
有时你可能希望调用对象实例上的方法,同时允许容器自动注入该方法的依赖项。例如,给定以下类:
php
<?php
namespace App;
use App\Services\AppleMusic;
class PodcastStats
{
/**
* Generate a new podcast stats report.
*/
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) {
// ...
});容器事件
Service container 每次解析对象时都会触发一个事件。你可以使用 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) {
//
},
);
// 新绑定将触发 rebinding 闭包...
$this->app->bind(PodcastPublisher::class, TransistorPublisher::class);PSR-11
Laravel 的 service container 实现了 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 的实例。