php反射學習之依賴注入示例
本文實例講述了php反射學習之依賴注入。分享給大家供大家參考,具體如下:
先看代碼:
<?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!"); } // 取類的構造函數(shù) $constructor = $reflector->getConstructor(); // 取構造函數(shù)的參數(shù) $parameters = $constructor->getParameters(); // 遍歷參數(shù) foreach ($parameters as $key => $parameter) { // 獲取參數(shù)聲明的類 $injector = new ReflectionClass($parameter->getClass()->name); // 實例化參數(shù)聲明類并填入?yún)?shù)列表 $parameters[$key] = $injector->newInstance(); } // 使用參數(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
運行方式,在終端下執(zhí)行php run.php Hello World
可以看到,我們要執(zhí)行 HelloController 下的 WorldAction,
HelloController 的構造函數(shù)需要一個 TestModel類型的對象,
通過php 反射,我們實現(xiàn)了, TestModel 對象的自動注入,
上面的例子類似于一個請求分發(fā)的過程,是路由請求的分發(fā)的一部分,假如我們要接收一個請求 地址例如: /Hello/World
意思是要執(zhí)行 HelloController 下的 WorldAction 方法。
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
php mailer類調用遠程SMTP服務器發(fā)送郵件實現(xiàn)方法
這篇文章主要介紹了php mailer類調用遠程SMTP服務器發(fā)送郵件實現(xiàn)方法,結合實例形式分析了php mailer類的調用及郵件發(fā)送相關技巧,需要的朋友可以參考下2016-03-03php mysql procedure實現(xiàn)獲取多個結果集的方法【基于thinkPHP】
這篇文章主要介紹了php mysql procedure實現(xiàn)獲取多個結果集的方法,基于thinkPHP實現(xiàn)針對數(shù)據(jù)庫多個結果集的相關操作技巧,需要的朋友可以參考下2016-11-11PHP封裝PDO實現(xiàn)操作MySql數(shù)據(jù)庫
數(shù)據(jù)庫操作類可以封裝數(shù)據(jù)庫連接和操作,使代碼更易于維護和擴展,這篇文章主要為大家詳細介紹了PHP如何封裝操作類PDO從而實現(xiàn)操作MySql數(shù)據(jù)庫的功能,需要的可以了解下2023-10-10