0
点赞
收藏
分享

微信扫一扫

laravel核心思想

NicoalsNC 2022-06-21 阅读 36

服务容器、依赖注入、门脸模式

服务容器


容器概念

  用来装一个个实例的对象,比如邮件类。 

IOC控制反转

  IOC(Inversion of Control)控制反转,面向对象,可降低代码之间的耦合度,借助第三方实现具有依赖关系的集合。

  laravel 容器位置:bootstrap/app.php 中

$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
//可通过 public/index.php $app = require_once __DIR__.'/../bootstrap/app.php'; 获取该路径

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'))});
解析 $this->app->make('HelpSpot\API');

laravel核心思想_依赖注入_02

 

DI依赖注入

DI依赖注入是一种设计思想,将实例遍历到对象中,laravel通过反射来完成。eg:

public function edit(Post $post){
  return view("post/edit",compact('post'));
}

 服务提供者


服务提供注册方法:

  1. register() //所有提供者提供服务之前提供
  2. boot() //所有提供者提供服务之后提供

延迟服务提供配置:

  protected $defer = true; 

服务提供位置:

  1. 配置文件:config/app.php providers=>[...]
  2. 框架中固定写好的:eg:注册服务 registerBaseServiceProviders() //position: vendor/laravel/framework/src/Illuminate/Foundation/Application.php

门脸模式


为容器中可用的类提供一种静态的调用方法  eg:\Request::all()

位置:config/app.php

eg:

aliases=>[
'Request' => Illuminate\Support\Facades\Request::class,
...
]

其实,所有的门脸类中只有一个方法,即返回对应的IOC控制反转中的标签

namespace Illuminate\Support\Facades;

/**
* @see \Illuminate\Http\Request
*/
class Request extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'request';
}
}

 示例分析日志类


查看日志:

tail -f storage/logs/laravel.log

laravel核心思想_依赖注入_03

1.容器


vendor/laravel/framework/src/Illuminate/Foundation/Application.php 中找到 registerBaseServiceProviders()方法,追踪到下面方法register(),可看出绑定到 log 字符串

public function register()
{
$this->app->singleton('log', function () {
return $this->createLogger();
});
}
code:
$app = app();               //获取容器
$log = $app->make('log'); //从容器中获取日志类,并解析(找到绑定的过程确定容器中字符串)
$log->info("post_index",['data'=>'hello log!']);

2.依赖注入


服务注册名字叫log可在当前文件找出设置的别名,其对应的三个别名都相当于获取log,position:vendor/laravel/framework/src/Illuminate/Foundation/Application.php,

'log'                  => [\Illuminate\Log\Writer::class, \Illuminate\Contracts\Logging\Log::class, \Psr\Log\LoggerInterface::class],

laravel核心思想_laravel_04

code:

public function index(\Illuminate\Log\Writer $log){
$log->info('post_index',['data'=>'hello log!']);
}

3.门脸模式:


通过 config/app.php 设置 aliases

'Request' => Illuminate\Support\Facades\Request::class,

laravel核心思想_laravel_05

 

code:

public function index(){
\Log::info('post_info',['data'=>'hello menlian!']);
}

 

举报

相关推荐

0 条评论