Laravel实现构造函数自动依赖注入的方法


Posted in PHP onMarch 16, 2016

本文实例讲述了Laravel实现构造函数自动依赖注入的方法。分享给大家供大家参考,具体如下:

在Laravel的构造函数中可以实现自动依赖注入,而不需要实例化之前先实例化需要的类,如代码所示:

<?php
namespace Lio\Http\Controllers\Forum;
use Lio\Forum\Replies\ReplyRepository;
use Lio\Forum\Threads\ThreadCreator;
use Lio\Forum\Threads\ThreadCreatorListener;
use Lio\Forum\Threads\ThreadDeleterListener;
use Lio\Forum\Threads\ThreadForm;
use Lio\Forum\Threads\ThreadRepository;
use Lio\Forum\Threads\ThreadUpdaterListener;
use Lio\Http\Controllers\Controller;
use Lio\Tags\TagRepository;
class ForumThreadsController extends Controller implements ThreadCreatorListener, ThreadUpdaterListener, ThreadDeleterListener
{
 protected $threads;
 protected $tags;
 protected $currentSection;
 protected $threadCreator;
 public function __construct(
  ThreadRepository $threads,
  ReplyRepository $replies,
  TagRepository $tags,
  ThreadCreator $threadCreator
 ) {
  $this->threads = $threads;
  $this->tags = $tags;
  $this->threadCreator = $threadCreator;
  $this->replies = $replies;
 }
}

注意构造函数中的几个类型约束,其实并没有地方实例化这个Controller并把这几个类型的参数传进去,Laravel会自动检测类的构造函数中的类型约束参数,并自动识别是否初始化并传入。

源码vendor/illuminate/container/Container.php中的build方法:

$constructor = $reflector->getConstructor();
dump($constructor);

这里会解析类的构造函数,在这里打印看:

Laravel实现构造函数自动依赖注入的方法

它会找出构造函数的参数,再看完整的build方法进行的操作:

public function build($concrete, array $parameters = [])
{
 // If the concrete type is actually a Closure, we will just execute it and
 // hand back the results of the functions, which allows functions to be
 // used as resolvers for more fine-tuned resolution of these objects.
 if ($concrete instanceof Closure) {
  return $concrete($this, $parameters);
 }
 $reflector = new ReflectionClass($concrete);
 // If the type is not instantiable, the developer is attempting to resolve
 // an abstract type such as an Interface of Abstract Class and there is
 // no binding registered for the abstractions so we need to bail out.
 if (! $reflector->isInstantiable()) {
  $message = "Target [$concrete] is not instantiable.";
  throw new BindingResolutionContractException($message);
 }
 $this->buildStack[] = $concrete;
 $constructor = $reflector->getConstructor();
 // If there are no constructors, that means there are no dependencies then
 // we can just resolve the instances of the objects right away, without
 // resolving any other types or dependencies out of these containers.
 if (is_null($constructor)) {
  array_pop($this->buildStack);
  return new $concrete;
 }
 $dependencies = $constructor->getParameters();
 // Once we have all the constructor's parameters we can create each of the
 // dependency instances and then use the reflection instances to make a
 // new instance of this class, injecting the created dependencies in.
 $parameters = $this->keyParametersByArgument(
  $dependencies, $parameters
 );
 $instances = $this->getDependencies(
  $dependencies, $parameters
 );
 array_pop($this->buildStack);
 return $reflector->newInstanceArgs($instances);
}

具体从容器中获取实例的方法:

protected function resolveClass(ReflectionParameter $parameter)
{
 try {
  return $this->make($parameter->getClass()->name);
 }
 // If we can not resolve the class instance, we will check to see if the value
 // is optional, and if it is we will return the optional parameter value as
 // the value of the dependency, similarly to how we do this with scalars.
 catch (BindingResolutionContractException $e) {
  if ($parameter->isOptional()) {
   return $parameter->getDefaultValue();
  }
  throw $e;
 }
}

框架底层通过Reflection反射为开发节省了很多细节,实现了自动依赖注入。这里不做继续深入研究了。

写了一个模拟这个过程的类测试:

<?php
class kulou
{
 //
}
class junjun
{
 //
}
class tanteng
{
 private $kulou;
 private $junjun;
 public function __construct(kulou $kulou,junjun $junjun)
 {
  $this->kulou = $kulou;
  $this->junjun = $junjun;
 }
}
//$tanteng = new tanteng(new kulou(),new junjun());
$reflector = new ReflectionClass('tanteng');
$constructor = $reflector->getConstructor();
$dependencies = $constructor->getParameters();
print_r($dependencies);exit;

原理是通过ReflectionClass类解析类的构造函数,并且取出构造函数的参数,从而判断依赖关系,从容器中取,并自动注入。

转自:小谈博客 http://www.tantengvip.com/2016/01/laravel-construct-ioc/

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

PHP 相关文章推荐
超级简单的发送邮件程序
Oct 09 PHP
php生成缩略图的类代码
Oct 02 PHP
php学习笔记 php中面向对象三大特性之一[封装性]的应用
Jun 13 PHP
探讨捕获php错误信息方法的详解
Jun 09 PHP
50个PHP程序性能优化的方法
Jun 02 PHP
PHP微框架Dispatch简介
Jun 12 PHP
CI框架自动加载session出现报错的解决办法
Jun 17 PHP
Laravel 5框架学习之用户认证
Apr 09 PHP
Yii框架中sphinx索引配置方法解析
Oct 18 PHP
php+mysql实现简单登录注册修改密码网页
Nov 30 PHP
PHP实现函数内修改外部变量值的方法示例
Dec 28 PHP
PHP树形结构tree类用法示例
Feb 01 PHP
PHP 二维数组和三维数组的过滤
Mar 16 #PHP
详解php中反射的应用
Mar 15 #PHP
php实现图片上传并进行替换操作
Mar 15 #PHP
php模板引擎技术简单实现
Mar 15 #PHP
9个比较实用的php代码片段
Mar 15 #PHP
Laravel使用Caching缓存数据减轻数据库查询压力的方法
Mar 15 #PHP
php图片添加文字水印实现代码
Mar 15 #PHP
You might like
造就帕卡马拉的帕卡斯是怎么被发现的
2021/03/03 咖啡文化
Uchome1.2 1.5 代码学习 common.php
2009/04/24 PHP
thinkphp实现多语言功能(语言包)
2014/03/04 PHP
PHP性能优化大全(php.ini)
2016/05/20 PHP
php+ajax实现无刷新文件上传功能(ajaxuploadfile)
2018/02/11 PHP
php设计模式之状态模式实例分析【星际争霸游戏案例】
2020/03/26 PHP
给Javascript数组插入一条记录的代码
2007/08/30 Javascript
js word表格动态添加代码
2010/06/07 Javascript
javascript的switch用法注意事项分析
2015/02/02 Javascript
在JavaScript中处理字符串之link()方法的使用
2015/06/08 Javascript
AngularJS之ionic 框架下实现 Localstorage本地存储
2017/04/22 Javascript
NodeJs实现定时任务的示例代码
2017/12/05 NodeJs
js实现微信/QQ直接跳转到支付宝APP打开口令领红包功能
2018/01/09 Javascript
Vue cli 引入第三方JS和CSS的常用方法分享
2018/01/20 Javascript
微信小程序Getuserinfo解决方案图解
2018/08/24 Javascript
vue中子组件的methods中获取到props中的值方法
2018/08/27 Javascript
浅谈javascript事件环微任务和宏任务队列原理
2020/09/12 Javascript
[02:31]2018年度DOTA2最具人气选手-完美盛典
2018/12/16 DOTA
[03:33]TI9战队采访 - Infamous
2019/08/20 DOTA
python实现通过代理服务器访问远程url的方法
2015/04/29 Python
Python中用于返回绝对值的abs()方法
2015/05/14 Python
Python网络爬虫实例讲解
2016/04/28 Python
python3+PyQt5重新实现自定义数据拖放处理
2018/04/19 Python
python打开音乐文件的实例方法
2020/07/21 Python
python 多线程共享全局变量的优劣
2020/09/24 Python
CSS3 Media Queries(响应式布局可以让你定制不同的分辨率和设备)
2013/06/06 HTML / CSS
Myprotein台湾官方网站:全球领先的运动营养品牌
2018/12/10 全球购物
美国翻新电子产品商店:The Store
2019/10/08 全球购物
一篇.NET面试题
2014/09/29 面试题
名词解释型面试题(主要是网络)
2013/12/27 面试题
医学院学生的自我评价分享
2013/11/19 职场文书
大学生创业计划书的用途
2014/01/08 职场文书
合伙协议书范本
2014/04/21 职场文书
2014年远程教育工作总结
2014/12/09 职场文书
大学生党性分析材料
2014/12/19 职场文书
js前端面试常见浏览器缓存强缓存及协商缓存实例
2022/06/21 Javascript