本文實(shí)例講述了php反射學(xué)習(xí)之依賴注入。分享給大家供大家參考,具體如下:
先看代碼:
?php if (PHP_SAPI != 'cli') { exit('Please run it in terminal!'); } if ($argc 3) { exit('At least 2 arguments needed!'); } $controller = ucfirst($argv[1]) . 'Controller'; $action = 'action' . ucfirst($argv[2]); // 檢查類是否存在 if (!class_exists($controller)) { exit("Class $controller does not existed!"); } // 獲取類的反射 $reflector = new ReflectionClass($controller); // 檢查方法是否存在 if (!$reflector->hasMethod($action)) { exit("Method $action does not existed!"); } // 取類的構(gòu)造函數(shù) $constructor = $reflector->getConstructor(); // 取構(gòu)造函數(shù)的參數(shù) $parameters = $constructor->getParameters(); // 遍歷參數(shù) foreach ($parameters as $key => $parameter) { // 獲取參數(shù)聲明的類 $injector = new ReflectionClass($parameter->getClass()->name); // 實(shí)例化參數(shù)聲明類并填入?yún)?shù)列表 $parameters[$key] = $injector->newInstance(); } // 使用參數(shù)列表實(shí)例 controller 類 $instance = $reflector->newInstanceArgs($parameters); // 執(zhí)行 $instance->$action(); class HelloController { private $model; public function __construct(TestModel $model) { $this->model = $model; } public function actionWorld() { echo $this->model->property, PHP_EOL; } } class TestModel { public $property = 'property'; }
(以上代碼非原創(chuàng))將以上代碼保存為 run.php
運(yùn)行方式,在終端下執(zhí)行php run.php Hello World
可以看到,我們要執(zhí)行 HelloController 下的 WorldAction,
HelloController 的構(gòu)造函數(shù)需要一個 TestModel類型的對象,
通過php 反射,我們實(shí)現(xiàn)了, TestModel 對象的自動注入,
上面的例子類似于一個請求分發(fā)的過程,是路由請求的分發(fā)的一部分,假如我們要接收一個請求 地址例如: /Hello/World
意思是要執(zhí)行 HelloController 下的 WorldAction 方法。
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:麗江 十堰 衡陽 臨沂 鷹潭 重慶 巴彥淖爾 銅陵
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《php反射學(xué)習(xí)之依賴注入示例》,本文關(guān)鍵詞 php,反射,學(xué),習(xí)之,依賴,注入,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。