作者:sotoloraboin_678 | 来源:互联网 | 2020-08-21 08:43
依赖注入原理:依赖注入是一种允许我们从硬编码的依赖中解耦出来,从而在运行时或者编译时能够修改的软件设计模式,简而言之就是可以让我们在类的方法中更加方便的调用与之关联的类。
依赖注入原理:
依赖注入是一种允许我们从硬编码的依赖中解耦出来,从而在运行时或者编译时能够修改的软件设计模式。简而言之就是可以让我们在类的方法中更加方便的调用与之关联的类。
实例讲解:
假设有一个这样的类:
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类就是完成这个依赖注入任务的。
getParameters();
$params = array();
foreach ($parammeters 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社区 其它相关文章!