本文實(shí)例講述了php中的依賴(lài)注入。分享給大家供大家參考,具體如下:
依賴(lài)注入是一種允許我們從硬編碼的依賴(lài)中解耦出來(lái),從而在運(yùn)行時(shí)或者編譯時(shí)能夠修改的軟件設(shè)計(jì)模式。
我到現(xiàn)在依然不大明白上面“依賴(lài)注入”的定義是什么……
有興趣可以參考下《PHP之道》上面對(duì)“依賴(lài)注入”的 解釋。
http://laravel-china.github.io/php-the-right-way/#dependency_injection
簡(jiǎn)而言之就是可以讓我們?cè)陬?lèi)的方法中更加方便的調(diào)用與之關(guān)聯(lián)的類(lèi)。
假設(shè)我們有一個(gè)這樣的類(lèi)
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方法調(diào)用起來(lái)是不是很麻煩?上面的方法還只是有兩個(gè)參數(shù),如果有更多的參數(shù),我們就要實(shí)例化更多的對(duì)象作為參數(shù)。如果我們引入的“依賴(lài)注入”,調(diào)用方式將會(huì)是像下面這個(gè)樣子。
$obj = new dependencyInjection();
$obj->fun("Test","index");
我們上面的例子中,Test類(lèi)的index方法依賴(lài)于Demo和Apple類(lèi)。
“依賴(lài)注入”就是識(shí)別出所有方法“依賴(lài)”的類(lèi),然后作為參數(shù)值“注入”到該方法中。
dependencyInjection類(lèi)就是完成這個(gè)依賴(lài)注入任務(wù)的。
?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有時(shí)會(huì)用到多個(gè)model。如果我們使用了依賴(lài)注入和類(lèi)的自動(dòng)加載之后,我們就可以像下面這樣使用。
public function index(UserModel $userModel,MessageModel $messageModel){
$userList = $userModel->getAllUser();
$messageList = $messageModel->getAllMessage();
}
灰常方便~
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語(yǔ)法入門(mén)教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- php+laravel依賴(lài)注入知識(shí)點(diǎn)總結(jié)
- laravel框架中你所用到的依賴(lài)注入詳解
- 通過(guò)源碼解析Laravel的依賴(lài)注入
- Laravel實(shí)現(xiàn)構(gòu)造函數(shù)自動(dòng)依賴(lài)注入的方法
- PHP依賴(lài)注入容器知識(shí)點(diǎn)淺析
- php依賴(lài)注入知識(shí)點(diǎn)詳解
- php反射學(xué)習(xí)之依賴(lài)注入示例
- PHP依賴(lài)注入原理與用法分析
- 詳解Laravel框架的依賴(lài)注入功能