關於PHP中依賴注入的詳細介紹

 

依賴注入原理:php

依賴注入是一種容許咱們從硬編碼的依賴中解耦出來,從而在運行時或者編譯時可以修改的軟件設計模式。簡而言之就是能夠讓咱們在類的方法中更加方便的調用與之關聯的類。web

實例講解:設計模式

假設有一個這樣的類:mvc

1app

2框架

3編碼

4spa

5設計

63d

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

}

相關文章
相關標籤/搜索