服务容器
Laravel 中的容器
- 绑定 由 服务提供者进行
$this->app->bind('HelpSpot\Api', function($app){
return new HelpSpot\API($app->make('HttpClient'));
});
$this->app->singleton('HelpSpot\Api', function($app){
return new HelpSpot\API($app->make('HttpClient'));
});
- 解析
$api = $this->app->make('HelpSpot\Api');
IOC控制反转
https://xueyuanjun.com/post/769.html
DI依赖注入
设计思想,Laravel中使用反射来进行
服务提供者
-
服务注册
public function register()
在所有服务提供者提供服务前注册
public function boot()
在所有服务提供者加载后 -
延迟服务提供
protected $defer = true;
第一次使用时才进行加载
门脸模式
dd(\Request::all()); // 对应 app/config.php aliases 中定义的门脸类 'Request' => Illuminate\Support\Facades\Request::class,
class Request extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'request'; // 返回服务注册名
}
}
关联
// 容器中获取 Log 实例
public function index()
{
$app = app(); // 获取容器
/*
'log' 字符串为注册在服务容器的标识符
Application.php 中 `public function registerBaseServiceProviders` 的
`$this->register(new LogServiceProvider($this));` 进行注册
*/
$logger = $app->make("log");
$logger->info("post_index", ['data' => 'this is post index']);
}
// 依赖注入的方式
// Application.php 中的 `public function registerCoreContainerAliases()` 定义了别名
// 'log' => [\Illuminate\Log\LogManager::class, \Psr\Log\LoggerInterface::class],
public function index1(\Psr\Log\LoggerInterface $logger)
{
$logger->info("post_index", ['data' => 'this is post index']);
}
// 门脸方式
// config/app.php 中定义了 'Log' => Illuminate\Support\Facades\Log::class,
public function index2()
{
\Log::info("post_index", ['data' => 'this is post index']);
}