今天扣丁學堂PHP培訓老師給你們分享一篇關於PHP反射實際應用,結合實例形式分析了php使用反射實現自動生成文檔、實現MVC架構、實現單元測試等具體應用操做技巧。php
1.自動生成文檔微信
根據反射的分析類,接口,函數和方法的內部結構,方法和函數的參數,以及類的屬性和方法,能夠自動生成文檔。架構
<?php框架
class Student函數
{單元測試
const NORMAL = 1;學習
const FORBIDDEN = 2;測試
/**this
*/code
public $id;
/**
*/
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%-40s<br/>", 'Name', 'Access', 'Comment');
$attr = $ref->getProperties();
foreach ($attr as $row) {
printf("%-15s%-10s%-40s<br/>", $row->getName(), getAccess($row), getComment($row));
}
echo "常量列表:<br/>";
printf("%-15s%-10s<br/>", 'Name', 'Value');
$const = $ref->getConstants();
foreach ($const as $key => $val) {
printf("%-15s%-10s<br/>", $key, $val);
}
echo "<br/><br/>";
echo "方法列表<br/>";
printf("%-15s%-10s%-30s%-40s<br/>", 'Name', 'Access', 'Params', 'Comment');
$methods = $ref->getMethods();
foreach ($methods as $row) {
printf("%-15s%-10s%-30s%-40s<br/>", $row->getName(), getAccess($row), getParams($row), getComment($row));
}
// 獲取權限
function getAccess($method)
{
if ($method->isPublic()) {
return 'Public';
}
if ($method->isProtected()) {
return 'Protected';
}
if ($method->isPrivate()) {
return 'Private';
}
}
// 獲取方法參數信息
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] : '';
}
輸出結果:
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
二、實現MVC架構
如今好多框架都是MVC的架構,根據路由信息定位控制器($controller)和方法($method)的名稱,以後使用反射實現自動調用。
$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.實現單元測試
通常狀況下咱們會對函數和類進行測試,判斷其是否可以按咱們預期返回結果,咱們能夠用反射實現一個簡單通用的類測試用例。
<?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 "測試結果正確"; };
}
}
testEqual('Calc@plus', 3, [1, 2]);
echo "<br/>";
testEqual('Calc@minus', -1, [1, 2]);
這裏只是我簡單寫的一個測試用例,PHPUnit單元測試框架很大程度上依賴了Reflection的特性,能夠了解下。
4.配合DI容器解決依賴
Laravel等許多框架都是使用Reflection解決依賴注入問題,具體可查看Laravel源碼進行分析。
下面咱們代碼簡單實現一個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)
{
// 若是是匿名函數,直接執行,並返回結果 if ($className instanceof Closure) { return $className($this); } // 已是實例化對象的話,直接返回 if(is_object($className)) { return $className; } // 若是是類的話,使用反射加載 $ref = new ReflectionClass($className); // 監測類是否可實例化 if (!$ref->isInstantiable()) { throw new Exception('class' . $className . ' not find'); } // 獲取構造函數 $construtor = $ref->getConstructor(); // 無構造函數,直接實例化返回 if (is_null($construtor)) { return new $className; } // 獲取構造函數參數 $params = $construtor->getParameters(); // 解析構造函數 $dependencies = $this->getDependecies($params); // 建立新實例 return $ref->newInstanceArgs($dependencies);
}
// 分析參數,若是參數中出現依賴類,遞歸實例化
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;
}
// 設置默認值
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;//輸出結果爲3
以上就是關於
想要了解更多關於PHP開發方面內容的小夥伴,請關注扣丁學堂PHP培訓官網、微信等平臺,扣丁學堂IT職業在線學習教育有專業的PHP講師爲您指導,此外扣丁學堂老師精心推出的PHP視頻教程定能讓你快速掌握PHP從入門到精通開發實戰技能。