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 相关文章推荐
php中目录,文件操作详谈
Mar 19 PHP
PHP pathinfo()获得文件的路径、名称等信息说明
Sep 13 PHP
解析PHP正则提取或替换img标记属性
Jun 26 PHP
浅析php数据类型转换
Jan 09 PHP
解密ThinkPHP3.1.2版本之独立分组功能应用
Jun 19 PHP
php魔术变量用法实例详解
Nov 13 PHP
PHP中判断文件存在使用is_file还是file_exists?
Apr 03 PHP
php each 返回数组中当前的键值对并将数组指针向前移动一步实例
Nov 22 PHP
PHP中使用mpdf 导出PDF文件的实现方法
Oct 22 PHP
PHP模型Model类封装数据库操作示例
Mar 14 PHP
php实现获取近几日、月时间示例
Jul 06 PHP
PHP实现考试倒计时功能代码
Apr 16 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
博士208HAF收音机实习报告
2021/03/02 无线电
一个ubbcode的函数,速度很快.
2006/10/09 PHP
php数组函数序列之array_slice() - 在数组中根据条件取出一段值,并返回
2011/11/07 PHP
Javascript YUI 读码日记之 YAHOO.util.Dom - Part.3
2008/03/22 Javascript
asp.net+jquery滚动滚动条加载数据的下拉控件
2010/06/25 Javascript
基于jQuery的可以控制左右滚动及自动滚动效果的代码
2010/07/25 Javascript
jquery mobile changepage的三种传参方法介绍
2013/09/13 Javascript
基于dropdown.js实现的两款美观大气的二级导航菜单
2015/09/02 Javascript
详解iframe与frame的区别
2016/01/13 Javascript
JS实现支持Ajax验证的表单插件
2016/03/24 Javascript
JS简单生成两个数字之间随机数的方法
2016/08/03 Javascript
AngularJS入门教程引导程序
2016/08/18 Javascript
Javascript动画效果(1)
2016/10/11 Javascript
12306 刷票脚本及稳固刷票脚本(防挂)
2017/01/04 Javascript
微信小程序时间轴实现方法示例
2019/01/14 Javascript
如何优雅地在Node应用中进行错误异常处理
2019/11/25 Javascript
jQuery实现简单弹幕效果
2019/11/28 jQuery
JavaScript实现轮播图片完整代码
2020/03/07 Javascript
对python append 与浅拷贝的实例讲解
2018/05/04 Python
python中有关时间日期格式转换问题
2019/12/25 Python
Pytorch环境搭建与基本语法
2020/06/03 Python
Python openpyxl模块实现excel读写操作
2020/06/30 Python
python中id函数运行方式
2020/07/03 Python
如何基于Python实现word文档重新排版
2020/09/29 Python
Python3利用openpyxl读写Excel文件的方法实例
2021/02/03 Python
详解python3 GUI刷屏器(附源码)
2021/02/18 Python
css3打造一款漂亮的卡哇伊按钮
2013/03/20 HTML / CSS
盖尔斯工厂店:GUESS Factory
2020/01/21 全球购物
Windows和Linux动态库应用异同
2016/07/28 面试题
高三语文教学反思
2014/01/15 职场文书
节约用水倡议书
2014/04/16 职场文书
励志演讲稿800字
2014/08/21 职场文书
个人欠款协议书范本2014
2014/11/02 职场文书
应聘教师求职信范文
2015/03/20 职场文书
温馨祝福晨语:美丽的一天从我的问候开始
2019/11/28 职场文书
PostgreSQL通过oracle_fdw访问Oracle数据的实现步骤
2021/05/21 PostgreSQL