依赖注入原理:

依赖注入是一种允许我们从硬编码的依赖中解耦出来,从而在运行时或者编译时能够修改的软件设计模式。简而言之就是可以让我们在类的方法中更加方便的调用与之关联的类。

实例讲解:

假设有一个这样的类:

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

/**

 * created by phpstorm.

 * user: zhezhao

 * date: 2016/8/10

 * time: 19:18

 */

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();

}