依赖注入原理:
依赖注入是一种容许咱们从硬编码的依赖中解耦进去,从而正在运转时或许编译时可以修正的软件设计模式。简而言之就是能够让咱们正在类的办法中愈加不便的挪用与之联系关系的类。
实例解说:
假定有一个这样的类:
class Test { public function index(Demo $demo,Apple $apple){ $demo->show(); $apple->fun(); } }
假如想应用index办法咱们需求这样做:
$demo = new Demo(); $apple = new Apple(); $obj = new Test(); $obj->index($demo,$apple);
index办法挪用起来是否是很费事?下面的办法还只是有两个参数,假如有更多的参数,咱们就要实例化更多的工具作为参数。假如咱们引入的“依赖注入”,挪用形式将会是像上面这个样子。
$obj = new dependencyInjection(); $obj->fun("Test","index");
咱们下面的例子中,Test类的index办法依赖于Demo以及Apple类。
“依赖注入”就是辨认出一切办法“依赖”的类,而后作为参数值“注入”到该办法中。
dependencyInjection类就是实现这个依赖注入义务的。
<?php /** * Created by PhpStorm. * User: zhezhao * Date: 2016/8/10 * Time: 19:18 */ class dependencyInjection { function fun($className,$action){ $reflectionMethod = new ReflectionMethod($className,$action); $para妹妹eters = $reflectionMethod->getParameters(); $params = array(); foreach ($para妹妹eters as $item) { preg_match('/> ([^ ]*)/',$item,$arr); $class = trim($arr[1]); $params[] = new $class(); } $instance = new $className(); $res = call_user_func_array([$instance,$action],$params); return $res; } }
正在mvc框架中,control有时会用到多个model。假如咱们应用了依赖注入以及类的主动加载之后,咱们就能够像上面这样应用。
public function index(UserModel $userModel,MessageModel $messageModel){ $userList = $userModel->getAllUser(); $messageList = $messageModel->getAllMessage(); }
保举教程:PHP视频教程
以上就是对于PHP中依赖注入的具体引见的具体内容,更多请存眷资源魔其它相干文章!
标签: php php开发教程 php开发资料 php开发自学 依赖注入 详细介绍
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!