php+laravel依赖注入浅析
laravel容器包含控制反转和依赖注入,使用起来就是,先把对象bind好,需要时可以直接使用make来取就好。
通常我们的调用如下。
$config = $container->make('config');
$connection = new Connection($this->config);
比较好理解,这样的好处就是不用直接 new 一个实例了,方法传值没啥改变,还可以多处共享此实例。
但这跟依赖注入有什么关系,真正的依赖注入是不需给方法传递任何参数值,只需要指明方法参数类型,代码自动查找关系依赖自动注入。
这个特性在 laravel 的 Controller、Job 等处可以体现,如下:
class TestController extends Controller
{
public function anyConsole(Request $request, Auth $input)
{
//todo
}
}
我们来看下他是怎么实现自动依赖注入的:
由 index.php 调用 Kernel ,经过多层 Kernel 管道调用,再到 Router ,经过多层中间件管道调用。最终定位到
Illuminate/Routing/Route.php 第124行。
public function run(Request $request)
{
$this->container = $this->container ?: new Container;
try {
if (! is_string($this->action['uses'])) {
return $this->runCallable($request);
}
if ($this->customDispatcherIsBound()) {
return $this->runWithCustomDispatcher($request);
}
return $this->runController($request);
} catch (HttpResponseException $e) {
return $e->getResponse();
}
}
判断 $this->action['uses'](格式行如:\App\Http\Controller\Datacenter\RealTimeController@anyConsole)是否字符串, $this->customDispatcherIsBound判断是否绑定了用户自定义路由。然后跳转到 $this->runController($request)。
protected function runController(Request $request)
{
list($class, $method) = explode('@', $this->action['uses']);
$parameters = $this->resolveClassMethodDependencies(
$this->parametersWithoutNulls(), $class, $method
);
if (! method_exists($instance = $this->container->make($class), $method)) {
throw new NotFoundHttpException;
}
return call_user_func_array([$instance, $method], $parameters);
}
$this->resolveClassMethodDependencies 这个方法一看名字就知道是我们要找的方法。$this->parametersWithoutNulls()是过滤空字符,$class、$method分别行如:\App\Http\Controller\Datacenter\RealTimeController 与 anyConsole。
protected function resolveClassMethodDependencies(array $parameters, $instance, $method)
{
if (! method_exists($instance, $method)) {
return $parameters;
}
return $this->resolveMethodDependencies(
$parameters, new ReflectionMethod($instance, $method)
);
}
new ReflectionMethod($instance, $method) 是拿到类方法的反射对象,参见文档:http://www.php.net/manual/zh/class.reflectionmethod.php
下面跳转到Illuminate/Routing/RouteDependencyResolverTrait.php 第54行。
public function resolveMethodDependencies(array $parameters, ReflectionFunctionAbstract $reflector)
{
$originalParameters = $parameters;
foreach ($reflector->getParameters() as $key => $parameter) {
$instance = $this->transformDependency(
$parameter, $parameters, $originalParameters
);
if (! is_null($instance)) {
$this->spliceIntoParameters($parameters, $key, $instance);
}
}
return $parameters;
}
通过反射类方法得到类参数数组,然后遍历传递给 $this->transformDependency 方法。如果实例获取不到则调用 $this->spliceIntoParameters 清楚该参数。
protected function transformDependency(ReflectionParameter $parameter, $parameters, $originalParameters)
{
$class = $parameter->getClass();
if ($class && ! $this->alreadyInParameters($class->name, $parameters)) {
return $this->container->make($class->name);
}
}
终于看到了容器的影子,没错最终对象还是通过容器的 make 方法取出来的。至此参数就构造好了,然后最终会被 runController 方法的 call_user_func_array 回调。
总结:
1. 依赖注入原理其实就是利用类方法反射,取得参数类型,然后利用容器构造好实例。然后再使用回调函数调起。
2. 注入对象构造函数不能有参数。否则会报错。Missing argument 1
3. 依赖注入故然好,但它必须要由 Router 类调起,否则直接用 new方式是无法实现注入的。所以这就为什么只有 Controller 、Job 类才能用这个特性了。
php+laravel依赖注入浅析的更多相关文章
- laravel依赖注入浅析
laravel容器包含控制反转和依赖注入,使用起来就是,先把对象bind好,需要时可以直接使用make来取就好. 通常我们的调用如下. $config = $container->make('c ...
- Laravel 依赖注入原理
众所周知 Laravel 的文档对于依赖注入只写了如何使用,相信大多数人对于他的实现原理并不太清楚.虽然使用过程中并不需要关心她的原理,但是了解原理让你使用起来更自信.这个帖子就通过一个小 demo ...
- laravel依赖注入 容器
[看完就懂]Laravel 服务容器,IoC,DI DI DI就是常说的依赖注入,那么究竟什么是依赖注入呢? 打个比方,电脑(非笔记本哈)需要键盘和鼠标我们才能进行操作,这个‘需要’换句话说 ...
- Spring依赖注入浅析
1. 概念理解 依赖注入 谁注入谁? 依赖对象注入IoC容器. 控制反转 谁控制谁?控制什么? IoC容器控制对象,控制依赖对象的创建与注入. 为什么称为反转?创建.注入对象的控制权由程序员的主观意愿 ...
- laravel 依赖注入
<?php interface Animal{ public function attack(); public function talk(); } class People implemen ...
- laravel 依赖注入 接口设计
假设我现在需要做一个支付服务,那么我先设计一个接口 interface PayInterface{ public function pay(Order $order) : string; } 然后实现 ...
- 【转】理解 PHP 依赖注入 | Laravel IoC容器
Laravel框架的依赖注入确实很强大,并且通过容器实现依赖注入可以有选择性的加载需要的服务,减少初始化框架的开销,下面是我在网上看到的一个帖子,写的很好拿来与大家分享,文章从开始按照传统的类设计数据 ...
- Android Dagger依赖注入框架浅析
今天接触了Dagger这套android的依赖注入框架(DI框架).感觉跟Spring 的IOC差点儿相同吧.这个框架它的优点是它没有採用反射技术(Spring是用反射的),而是用预编译技术.因为基于 ...
- 通过laravel理解IoC(控制反转)容器和DI(依赖注入)
原文地址: http://www.insp.top/learn-laravel-container ,转载务必保留来源,谢谢了! 容器,字面上理解就是装东西的东西.常见的变量.对象属性等都可以算是容器 ...
随机推荐
- 前端开发规范:4-JS
ESLint 使用ESLint的standard规范来编写js代码 更多参考: https://github.com/standard/standard/blob/master/docs/README ...
- 知识图谱基础之RDF,RDFS与OWL 2
https://zhuanlan.zhihu.com/p/32122644 看过之前两篇文章([1](为什么需要知识图谱?什么是知识图谱?——KG的前世今生), [2](语义网络,语义网,链接数据和知 ...
- datatable的dom配置
l - Length changing 改变每页显示多少条数据的控件 f - Filtering input 即时搜索框控件 t - The Table 表格本身 i - Information 表格 ...
- JS Proxy(代理)
前言 Proxy 也就是代理,可以帮助我们完成很多事情,例如对数据的处理,对构造函数的处理,对数据的验证,说白了,就是在我们访问对象前添加了一层拦截,可以过滤很多操作,而这些过滤,由你来定义. 想了解 ...
- C++继承产生的问题
今天写代码,用到了继承,忘了将父类中的私有成员改为protected,结果一调用父类地函数后,子类中的root指针直接变为了父类中的空的root.私有成员在继承后依然会保留,占一定的内存空间,但却没有 ...
- IT兄弟连 HTML5教程 HTML5做到了与之前版本的兼容
为了保证HTML5能与之前的HTML版本达到最大的兼容,HTML5对一些元素标记的省略.boolean值的属性,以及引号的省略这几方面进行了兼顾,确保与之前版本的HTML达到兼容.在下面示例中,将本节 ...
- 【转载】【PAT】PAT甲级题型分类整理
最短路径 Emergency (25)-PAT甲级真题(Dijkstra算法) Public Bike Management (30)-PAT甲级真题(Dijkstra + DFS) Travel P ...
- vs 2019 自带 反编译 与 Reflector 反编译工具比较
都是一样的 但是要看自己写的 反编译代码 还是得去 Reflector
- 如何优雅规避NPE
项目中尤其是在持久层,难免会有大量的针对集合,对象,字符串的操作,为了程序的健壮性,我们不得不进行判空,像下面箭头式编码吗? if(null!=person){ ... if(null!=addres ...
- PAT 1005 Spell It Right 字符串处理
Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output e ...