亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

php反射學習之依賴注入示例

 更新時間:2019年06月14日 11:03:24   作者:ltx06  
這篇文章主要介紹了php反射學習之依賴注入,結合具體實例形式分析了php基于反射的依賴注入原理與實現(xiàn)方法,需要的朋友可以參考下

本文實例講述了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程序設計有所幫助。

相關文章

最新評論