我需要知道使用服务容器标记的目的是什么以及如何通过示例使用它,这是我到目前为止所尝试的。
class MemoryReport
{
}
class SpeedReport
{
}
class ReportAggregator
{
public function __construct(MemoryReport $memory, SpeedReport $speed)
{
}
}
App::bind('MemoryReport', function () {
return new MemoryReport;
});
App::bind('SpeedReport', function () {
return new SpeedReport;
});
App::tag(['MemoryReport', 'SpeedReport'], 'reports');
App::bind('ReportAggregator', function ($app) {
return new ReportAggregator($app->tagged('reports'));
});
$reportAggregator = resolve('ReportAggregator');
dd($reportAggregator);
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误。
传递给 ReportAggregator::__construct() 的参数 1 必须是 MemoryReport 的实例,给出的 Illuminate\Container\RewindableGenerator 的实例,在 /media/mazzam/9068A9DC68A9C0F81/M.azzam/Learning/laravel/00 Tutorial/tut/routes/ 中调用web.php 第 80 行
在Laravel的服务容器中,我可以绑定单例和实例。来自 Laravel文档:
绑定单例
单例方法将一个类或接口绑定到容器中,该容器只应解析一次。一旦解析了单例绑定,后续调用容器时将返回相同的对象实例:
Run Code Online (Sandbox Code Playgroud)$this->app->singleton('HelpSpot\API', function ($app) { return new HelpSpot\API($app->make('HttpClient')); });
绑定实例
您还可以使用实例方法将现有对象实例绑定到容器中。给定的实例将始终在后续调用容器时返回:
Run Code Online (Sandbox Code Playgroud)$api = new HelpSpot\API(new HttpClient); $this->app->instance('HelpSpot\API', $api);
Q1)那么这两个概念有什么区别?我可以猜测,对于单例绑定,Laravel 在第一次请求时通过内部服务容器机制构建对象本身,然后在后续调用中提供它,而在实例绑定的情况下,服务容器会显式地给出一个已经构建的对象,它在每个要求?
或者还有其他的解释吗?
Q2)为什么我们需要这两种绑定选项?
需要通过一个例子来了解 Laravel 服务容器和服务提供者。