本文實(shí)例講述了PHP反射實(shí)際應(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();
// 簡單的獲取了第一行的信息,這里可以自行擴(kuò)展
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.實(shí)現(xiàn) MVC 架構(gòu)
現(xiàn)在好多框架都是 MVC 的架構(gòu),根據(jù)路由信息定位控制器($controller) 和方法($method) 的名稱,之后使用反射實(shí)現(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.實(shí)現(xiàn)單元測試
一般情況下我們會對函數(shù)和類進(jìn)行測試,判斷其是否能夠按我們預(yù)期返回結(jié)果,我們可以用反射實(shí)現(xiàn)一個(gè)簡單通用的類測試用例。
?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]);
這是類的測試方法,也可以利用反射實(shí)現(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'));
?>
這里只是我簡單寫的一個(gè)測試用例,PHPUnit 單元測試框架很大程度上依賴了 Reflection 的特性,可以了解下。
4.配合 DI 容器解決依賴
Laravel 等許多框架都是使用 Reflection 解決依賴注入問題,具體可查看 Laravel 源碼進(jìn)行分析。
下面我們代碼簡單實(shí)現(xiàn)一個(gè) 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]);
}
// 獲取實(shí)例
public function bulid($className)
{
// 如果是匿名函數(shù),直接執(zhí)行,并返回結(jié)果
if ($className instanceof Closure) {
return $className($this);
}
// 已經(jīng)是實(shí)例化對象的話,直接返回
if(is_object($className)) {
return $className;
}
// 如果是類的話,使用反射加載
$ref = new ReflectionClass($className);
// 監(jiān)測類是否可實(shí)例化
if (!$ref->isInstantiable()) {
throw new Exception('class' . $className . ' not find');
}
// 獲取構(gòu)造函數(shù)
$construtor = $ref->getConstructor();
// 無構(gòu)造函數(shù),直接實(shí)例化返回
if (is_null($construtor)) {
return new $className;
}
// 獲取構(gòu)造函數(shù)參數(shù)
$params = $construtor->getParameters();
// 解析構(gòu)造函數(shù)
$dependencies = $this->getDependecies($params);
// 創(chuàng)建新實(shí)例
return $ref->newInstanceArgs($dependencies);
}
// 分析參數(shù),如果參數(shù)中出現(xiàn)依賴類,遞歸實(shí)例化
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è)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- PHP的反射動態(tài)獲取類方法、屬性、參數(shù)操作示例
- php面試實(shí)現(xiàn)反射注入的詳細(xì)方法
- PHP反射原理與用法深入分析
- php提供實(shí)現(xiàn)反射的方法和實(shí)例代碼
- PHP進(jìn)階學(xué)習(xí)之反射基本概念與用法分析
- php反射學(xué)習(xí)之不用new方法實(shí)例化類操作示例
- PHP反射學(xué)習(xí)入門示例
- 用PHP的反射實(shí)現(xiàn)委托模式的講解
- 淺析PHP類的反射來實(shí)現(xiàn)依賴注入過程
- PHP基于反射機(jī)制實(shí)現(xiàn)自動依賴注入的方法詳解
- PHP基于反射獲取一個(gè)類中所有的方法
- PHP反射基礎(chǔ)知識回顧