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相关资料
Oct 09 PHP
PHP学习之正则表达式
Apr 17 PHP
深入php多态的实现详解
Jun 09 PHP
destoon利用Rewrite规则设置网站安全
Jun 21 PHP
php实现文件下载代码分享
Aug 19 PHP
php模拟服务器实现autoindex效果的方法
Mar 10 PHP
php数组函数array_walk用法示例
May 26 PHP
php字符串操作针对负值的判断分析
Jul 28 PHP
PHP+MYSQL实现读写分离简单实战
Mar 13 PHP
PHP使用反向Ajax技术实现在线客服系统详解
Jul 01 PHP
关于laravel-admin ueditor 集成并解决刷新的问题
Oct 21 PHP
laravel返回统一格式错误码问题
Nov 04 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
动易数据转成dedecms的php程序
2007/04/07 PHP
php缩小png图片不损失透明色的解决方法
2013/12/25 PHP
PHP提交表单失败后如何保留已经填写的信息
2014/06/20 PHP
php开发中的页面跳转方法总结
2015/04/26 PHP
laravel通过创建自定义artisan make命令来新建类文件详解
2017/08/17 PHP
Javascript客户端将指定区域导出到Word、Excel的代码
2008/10/22 Javascript
js function使用心得
2010/05/10 Javascript
有关javascript的性能优化 (repaint和reflow)
2013/04/12 Javascript
JavaScript基本的输出和嵌入式写法教程
2015/10/20 Javascript
js实现table添加行tr、删除行tr、清空行tr的简单实例
2016/10/15 Javascript
laydate.js日期时间选择插件
2017/01/04 Javascript
Bootstrap导航条鼠标悬停下拉菜单
2017/01/04 Javascript
使用jquery+iframe做一个ajax上传效果(实例)
2017/08/24 jQuery
JS实现多物体运动的方法详解
2018/01/23 Javascript
JS插件clipboard.js实现一键复制粘贴功能
2020/12/04 Javascript
浅谈在vue中使用mint-ui swipe遇到的问题
2018/09/27 Javascript
javascript canvas API内容整理
2020/02/16 Javascript
利用aardio给python编写图形界面
2017/08/21 Python
使用Python从零开始撸一个区块链
2018/03/14 Python
python中删除某个元素的方法解析
2019/11/05 Python
tensorflow-gpu安装的常见问题及解决方案
2020/01/20 Python
Python运行提示缺少模块问题解决方案
2020/04/02 Python
keras .h5转移动端的.tflite文件实现方式
2020/05/25 Python
一家专门做特卖的网站:唯品会
2016/10/09 全球购物
介绍一下Linux文件的记录形式
2013/09/29 面试题
会计师事务所审计实习自我鉴定
2013/09/20 职场文书
书法培训心得体会
2014/01/05 职场文书
决心书标准格式
2014/03/11 职场文书
给校长的建议书
2014/03/12 职场文书
作风年建设汇报材料
2014/08/14 职场文书
2014年作风建设剖析材料
2014/10/23 职场文书
自我推荐信格式模板
2015/03/24 职场文书
2015年班组工作总结
2015/04/20 职场文书
vue前端工程的搭建
2021/03/31 Vue.js
python 如何做一个识别率百分百的OCR
2021/05/29 Python
Python学习之迭代器详解
2022/04/01 Python