依赖注入原理:
依赖注入是一种允许我们从硬编码的依赖中解耦出来,从而在运行时或者编译时能够修改的软件设计模式。简而言之就是可以让我们在类的方法中更加方便的调用与之关联的类。
实例讲解:
假设有一个这样的类:
|
1
2
3
4
5
6
7
|
class Test
{
public function index(Demo $demo,Apple $apple){
$demo->show();
$apple->fun();
}
}
|
如果想使用index方法我们需要这样做:
|
1
2
3
4
|
$demo = new Demo();
$apple = new Apple();
$obj = new Test();
$obj->index($demo,$apple);
|
index方法调用起来是不是很麻烦?上面的方法还只是有两个参数,如果有更多的参数,我们就要实例化更多的对象作为参数。如果我们引入的“依赖注入”,调用方式将会是像下面这个样子。
|
1
2
|
$obj = new dependencyInjection();
$obj->fun("Test","index");
|
我们上面的例子中,Test类的index方法依赖于Demo和Apple类。
“依赖注入”就是识别出所有方法“依赖”的类,然后作为参数值“注入”到该方法中。
dependencyInjection类就是完成这个依赖注入任务的。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?php
class dependencyInjection
{
function fun($className,$action){
$reflectionMethod = new ReflectionMethod($className,$action);
$parammeters = $reflectionMethod->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。如果我们使用了依赖注入和类的自动加载之后,我们就可以像下面这样使用。
|
1
2
3
4
|
public function index(UserModel $userModel,MessageModel $messageModel){
$userList = $userModel->getAllUser();
$messageList = $messageModel->getAllMessage();
}
|