佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > PHP反射實際應(yīng)用示例

PHP反射實際應(yīng)用示例

熱門標(biāo)簽:電子圍欄 銀行業(yè)務(wù) 科大訊飛語音識別系統(tǒng) Mysql連接數(shù)設(shè)置 服務(wù)器配置 Linux服務(wù)器 阿里云 團(tuán)購網(wǎng)站

本文實例講述了PHP反射實際應(yīng)用。分享給大家供大家參考,具體如下:

1.自動生成文檔

根據(jù)反射的分析類,接口,函數(shù)和方法的內(nèi)部結(jié)構(gòu),方法和函數(shù)的參數(shù),以及類的屬性和方法,可以自動生成文檔。

?php
class Student
{
  const NORMAL = 1;
  const FORBIDDEN = 2;
  /**
   * 用戶ID
   * @var 類型
   */
  public $id;
  /**
   * 獲取id
   * @return int
   */
  public function getId()
  {
    return $this->id;
  }
  public function setId($id = 1)
  {
    $this->id = $id;
  }
}
$ref = new ReflectionClass('Student');
$doc = $ref->getDocComment();
echo $ref->getName() . ':' . getComment($ref) , "br/>";
echo "屬性列表:br/>";
printf("%-15s%-10s%-40sbr/>", 'Name', 'Access', 'Comment');
$attr = $ref->getProperties();
foreach ($attr as $row) {
  printf("%-15s%-10s%-40sbr/>", $row->getName(), getAccess($row), getComment($row));
}
echo "常量列表:br/>";
printf("%-15s%-10sbr/>", 'Name', 'Value');
$const = $ref->getConstants();
foreach ($const as $key => $val) {
  printf("%-15s%-10sbr/>", $key, $val);
}
echo "br/>br/>";
echo "方法列表br/>";
printf("%-15s%-10s%-30s%-40sbr/>", 'Name', 'Access', 'Params', 'Comment');
$methods = $ref->getMethods();
foreach ($methods as $row) {
  printf("%-15s%-10s%-30s%-40sbr/>", $row->getName(), getAccess($row), getParams($row), getComment($row));
}
// 獲取權(quán)限
function getAccess($method)
{
  if ($method->isPublic()) {
    return 'Public';
  }
  if ($method->isProtected()) {
    return 'Protected';
  }
  if ($method->isPrivate()) {
    return 'Private';
  }
}
// 獲取方法參數(shù)信息
function getParams($method)
{
  $str = '';
  $parameters = $method->getParameters();
  foreach ($parameters as $row) {
    $str .= $row->getName() . ',';
    if ($row->isDefaultValueAvailable()) {
      $str .= "Default: {$row->getDefaultValue()}";
    }
  }
  return $str ? $str : '';
}
// 獲取注釋
function getComment($var)
{
  $comment = $var->getDocComment();
  // 簡單的獲取了第一行的信息,這里可以自行擴展
  preg_match('/\* (.*) *?/', $comment, $res);
  return isset($res[1]) ? $res[1] : '';
}

輸出結(jié)果:

Student:
屬性列表:
Name Access Comment
id Public 用戶ID
常量列表:
Name Value
NORMAL 1
FORBIDDEN 2
方法列表
Name Access Params Comment
getId Public 獲取id
setId Public id,Default: 1

2.實現(xiàn) MVC 架構(gòu)

現(xiàn)在好多框架都是 MVC 的架構(gòu),根據(jù)路由信息定位控制器($controller) 和方法($method) 的名稱,之后使用反射實現(xiàn)自動調(diào)用。

$class = new ReflectionClass(ucfirst($controller) . 'Controller');
$controller = $class->newInstance();
if ($class->hasMethod($method)) {
  $method = $class->getMethod($method);
  $method->invokeArgs($controller, $arguments);
} else {
  throw new Exception("{$controller} controller method {$method} not exists!");
}

3.實現(xiàn)單元測試

一般情況下我們會對函數(shù)和類進(jìn)行測試,判斷其是否能夠按我們預(yù)期返回結(jié)果,我們可以用反射實現(xiàn)一個簡單通用的類測試用例。

?php
class Calc
{
  public function plus($a, $b)
  {
    return $a + $b;
  }
  public function minus($a, $b)
  {
    return $a - $b;
  }
}
function testEqual($method, $assert, $data)
{
  $arr = explode('@', $method);
  $class = $arr[0];
  $method = $arr[1];
  $ref = new ReflectionClass($class);
  if ($ref->hasMethod($method)) {
    $method = $ref->getMethod($method);
    $res = $method->invokeArgs(new $class, $data);
    if($res === $assert){
      echo "測試結(jié)果正確";
    };
  }
}
testEqual('Calc@plus', 3, [1, 2]);
echo "br/>";
testEqual('Calc@minus', -1, [1, 2]);

這是類的測試方法,也可以利用反射實現(xiàn)函數(shù)的測試方法。

?php
function title($title, $name)
{
  return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
echo $function->invokeArgs(array('Dr', 'Phil'));
?>

這里只是我簡單寫的一個測試用例,PHPUnit 單元測試框架很大程度上依賴了 Reflection 的特性,可以了解下。

4.配合 DI 容器解決依賴

Laravel 等許多框架都是使用 Reflection 解決依賴注入問題,具體可查看 Laravel 源碼進(jìn)行分析。

下面我們代碼簡單實現(xiàn)一個 DI 容器演示 Reflection 解決依賴注入問題。

?php
class DI
{
  protected static $data = [];
  public function __set($k, $v)
  {
    self::$data[$k] = $v;
  }
  public function __get($k)
  {
    return $this->bulid(self::$data[$k]);
  }
  // 獲取實例
  public function bulid($className)
  {
    // 如果是匿名函數(shù),直接執(zhí)行,并返回結(jié)果
    if ($className instanceof Closure) {
      return $className($this);
    }
    // 已經(jīng)是實例化對象的話,直接返回
    if(is_object($className)) {
      return $className;
    }
    // 如果是類的話,使用反射加載
    $ref = new ReflectionClass($className);
    // 監(jiān)測類是否可實例化
    if (!$ref->isInstantiable()) {
      throw new Exception('class' . $className . ' not find');
    }
    // 獲取構(gòu)造函數(shù)
    $construtor = $ref->getConstructor();
    // 無構(gòu)造函數(shù),直接實例化返回
    if (is_null($construtor)) {
      return new $className;
    }
    // 獲取構(gòu)造函數(shù)參數(shù)
    $params = $construtor->getParameters();
    // 解析構(gòu)造函數(shù)
    $dependencies = $this->getDependecies($params);
    // 創(chuàng)建新實例
    return $ref->newInstanceArgs($dependencies);
  }
  // 分析參數(shù),如果參數(shù)中出現(xiàn)依賴類,遞歸實例化
  public function getDependecies($params)
  {
    $data = [];
    foreach($params as $param)
    {
      $tmp = $param->getClass();
      if (is_null($tmp)) {
        $data[] = $this->setDefault($param);
      } else {
        $data[] = $this->bulid($tmp->name);
      }
    }
    return $data;
  }
  // 設(shè)置默認(rèn)值
  public function setDefault($param)
  {
    if ($param->isDefaultValueAvailable()) {
      return $param->getDefaultValue();
    }
    throw new Exception('no default value!');
  }
}
class Demo
{
  public function __construct(Calc $calc)
  {
    echo $calc->plus(1, 2);
  }
}
class Calc
{
  public function plus($a, $b)
  {
    return $a + $b;
  }
  public function minus($a, $b)
  {
    return $a - $b;
  }
}
$di = new DI();
$di->calc = 'Calc';
$di->demo = 'Demo';
$di->demo;//輸出結(jié)果為3

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

希望本文所述對大家PHP程序設(shè)計有所幫助。

您可能感興趣的文章:
  • PHP的反射動態(tài)獲取類方法、屬性、參數(shù)操作示例
  • php面試實現(xiàn)反射注入的詳細(xì)方法
  • PHP反射原理與用法深入分析
  • php提供實現(xiàn)反射的方法和實例代碼
  • PHP進(jìn)階學(xué)習(xí)之反射基本概念與用法分析
  • php反射學(xué)習(xí)之不用new方法實例化類操作示例
  • PHP反射學(xué)習(xí)入門示例
  • 用PHP的反射實現(xiàn)委托模式的講解
  • 淺析PHP類的反射來實現(xiàn)依賴注入過程
  • PHP基于反射機制實現(xiàn)自動依賴注入的方法詳解
  • PHP基于反射獲取一個類中所有的方法
  • PHP反射基礎(chǔ)知識回顧

標(biāo)簽:蚌埠 萍鄉(xiāng) 棗莊 廣元 江蘇 衡水 大理 衢州

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP反射實際應(yīng)用示例》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    静海县| 军事| 明溪县| 互助| 德昌县| 报价| 咸丰县| 平乡县| 龙州县| 大埔区| 定远县| 马山县| 迁安市| 闽清县| 都兰县| 昌黎县| 平和县| 电白县| 乌苏市| 环江| 丰台区| 延庆县| 中宁县| 高台县| 浦县| 武城县| 韶山市| 朝阳区| 武定县| 吉隆县| 盘锦市| 广河县| 永兴县| 安平县| 涪陵区| 伊金霍洛旗| 扶风县| 嘉定区| 佛山市| 富顺县| 改则县|