依賴注入原理:
依賴注入是一種允許我們從硬編碼的依賴中解耦出來,從而在運行時或者編譯時能夠修改的軟體設計模式,簡而言之就是可以讓我們在類的方法中更加方便的呼叫與之關聯的類,
實體講解:
假設有一個這樣的類:
|
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();
}
|
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/116803.html
標籤:PHP
上一篇:PHP中介面與抽象類的異同點有哪些
下一篇:PHP中Redis擴展無法加載問題