最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PHP?parser重寫PHP類使用示例詳解

 更新時(shí)間:2023年09月08日 14:05:15   作者:李銘昕  
這篇文章主要為大家介紹了PHP?parser重寫PHP類使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

引言

最近一直在研究 Swoft 框架,框架核心當(dāng)然是 Aop 切面編程,所以想把這部分的心得記下來,以供后期查閱。

Swoft 新版的 Aop 設(shè)計(jì)建立在 PHP Parser 上面。所以這片文章,主要介紹一下 PHP Parser 在 Aop 編程中的使用。

Test 類

簡單的來講,我們想在某些類的方法上進(jìn)行埋點(diǎn),比如下面的 Test 類。

class Test {
    public function get() {
            // do something
        }
}

我們想讓它的 get 方法變成以下的樣子

class Test {
    public function get() {
            // do something before
            // do something
                // do something after
        }
}

最簡單的設(shè)計(jì)就是,我們使用 parser 生成對(duì)應(yīng)的語法樹,然后主動(dòng)修改方法體內(nèi)的邏輯。

接下來,我們就是用 PHP Parser 來搞定這件事。

首先我們先定一個(gè) ProxyVisitor

Visitor 有四個(gè)方法,其中

  • beforeTraverse () 方法用于遍歷之前,通常用來在遍歷前對(duì)值進(jìn)行重置。
  • afterTraverse () 方法和(1)相同,唯一不同的地方是遍歷之后才觸發(fā)。
  • enterNode () 和 leaveNode () 方法在對(duì)每個(gè)節(jié)點(diǎn)訪問時(shí)觸發(fā)。
<?php
namespace App\Aop;
use PhpParser\NodeVisitorAbstract;
use PhpParser\Node;
class ProxyVisitor extends NodeVisitorAbstract
{
? ? public function leaveNode(Node $node)
? ? {
? ? }
? ? public function afterTraverse(array $nodes)
? ? {
? ? }
}

我們要做的就是重寫 leaveNode,讓我們遍歷語法樹的時(shí)候,把類方法里的邏輯重置掉。另外就是重寫 afterTraverse 方法,讓我們遍歷結(jié)束之后,把我們的 AopTrait 扔到類里。AopTrait 就是我們賦予給類的,切面編程的能力。

創(chuàng)建一個(gè)測試類

首先,我們先創(chuàng)建一個(gè)測試類,來看看 parser 生成的語法樹是什么樣子的

namespace App;
class Test
{
? ? public function show()
? ? {
? ? ? ? return 'hello world';
? ? }
}
use PhpParser\ParserFactory;
use PhpParser\NodeDumper;
$file = APP_PATH . '/Test.php';
$code = file_get_contents($file);
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse($code);
$dumper = new NodeDumper();
echo $dumper->dump($ast) . "\n";
結(jié)果樹如下
array(
? ? 0: Stmt_Namespace(
? ? ? ? name: Name(
? ? ? ? ? ? parts: array(
? ? ? ? ? ? ? ? 0: App
? ? ? ? ? ? )
? ? ? ? )
? ? ? ? stmts: array(
? ? ? ? ? ? 0: Stmt_Class(
? ? ? ? ? ? ? ? flags: 0
? ? ? ? ? ? ? ? name: Identifier(
? ? ? ? ? ? ? ? ? ? name: Test
? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? extends: null
? ? ? ? ? ? ? ? implements: array(
? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? stmts: array(
? ? ? ? ? ? ? ? ? ? 0: Stmt_ClassMethod(
? ? ? ? ? ? ? ? ? ? ? ? flags: MODIFIER_PUBLIC (1)
? ? ? ? ? ? ? ? ? ? ? ? byRef: false
? ? ? ? ? ? ? ? ? ? ? ? name: Identifier(
? ? ? ? ? ? ? ? ? ? ? ? ? ? name: show
? ? ? ? ? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? ? ? ? ? params: array(
? ? ? ? ? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? ? ? ? ? returnType: null
? ? ? ? ? ? ? ? ? ? ? ? stmts: array(
? ? ? ? ? ? ? ? ? ? ? ? ? ? 0: Stmt_Return(
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? expr: Scalar_String(
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? value: hello world
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? ? ? )
? ? ? ? ? ? ? ? )
? ? ? ? ? ? )
? ? ? ? )
? ? )
)

語法樹的具體含義,我就不贅述了,感興趣的同學(xué)直接去看一下 PHP Parser 的文檔吧。(其實(shí)我也沒全都看完。。。大體知道而已,哈哈哈)

接下來重寫我們的 ProxyVisitor

<?php
namespace App\Aop;
use PhpParser\NodeVisitorAbstract;
use PhpParser\Node;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\TraitUse;
use PhpParser\NodeFinder;
class ProxyVisitor extends NodeVisitorAbstract
{
? ? protected $className;
? ? protected $proxyId;
? ? public function __construct($className, $proxyId)
? ? {
? ? ? ? $this->className = $className;
? ? ? ? $this->proxyId = $proxyId;
? ? }
? ? public function getProxyClassName(): string
? ? {
? ? ? ? return \basename(str_replace('\\', '/', $this->className)) . '_' . $this->proxyId;
? ? }
? ? public function getClassName()
? ? {
? ? ? ? return '\\' . $this->className . '_' . $this->proxyId;
? ? }
? ? /**
? ? ?* @return \PhpParser\Node\Stmt\TraitUse
? ? ?*/
? ? private function getAopTraitUseNode(): TraitUse
? ? {
? ? ? ? // Use AopTrait trait use node
? ? ? ? return new TraitUse([new Name('\App\Aop\AopTrait')]);
? ? }
? ? public function leaveNode(Node $node)
? ? {
? ? ? ? // Proxy Class
? ? ? ? if ($node instanceof Class_) {
? ? ? ? ? ? // Create proxy class base on parent class
? ? ? ? ? ? return new Class_($this->getProxyClassName(), [
? ? ? ? ? ? ? ? 'flags' => $node->flags,
? ? ? ? ? ? ? ? 'stmts' => $node->stmts,
? ? ? ? ? ? ? ? 'extends' => new Name('\\' . $this->className),
? ? ? ? ? ? ]);
? ? ? ? }
? ? ? ? // Rewrite public and protected methods, without static methods
? ? ? ? if ($node instanceof ClassMethod && !$node->isStatic() && ($node->isPublic() || $node->isProtected())) {
? ? ? ? ? ? $methodName = $node->name->toString();
? ? ? ? ? ? // Rebuild closure uses, only variable
? ? ? ? ? ? $uses = [];
? ? ? ? ? ? foreach ($node->params as $key => $param) {
? ? ? ? ? ? ? ? if ($param instanceof Param) {
? ? ? ? ? ? ? ? ? ? $uses[$key] = new Param($param->var, null, null, true);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? $params = [
? ? ? ? ? ? ? ? // Add method to an closure
? ? ? ? ? ? ? ? new Closure([
? ? ? ? ? ? ? ? ? ? 'static' => $node->isStatic(),
? ? ? ? ? ? ? ? ? ? 'uses' => $uses,
? ? ? ? ? ? ? ? ? ? 'stmts' => $node->stmts,
? ? ? ? ? ? ? ? ]),
? ? ? ? ? ? ? ? new String_($methodName),
? ? ? ? ? ? ? ? new FuncCall(new Name('func_get_args')),
? ? ? ? ? ? ];
? ? ? ? ? ? $stmts = [
? ? ? ? ? ? ? ? new Return_(new MethodCall(new Variable('this'), '__proxyCall', $params))
? ? ? ? ? ? ];
? ? ? ? ? ? $returnType = $node->getReturnType();
? ? ? ? ? ? if ($returnType instanceof Name && $returnType->toString() === 'self') {
? ? ? ? ? ? ? ? $returnType = new Name('\\' . $this->className);
? ? ? ? ? ? }
? ? ? ? ? ? return new ClassMethod($methodName, [
? ? ? ? ? ? ? ? 'flags' => $node->flags,
? ? ? ? ? ? ? ? 'byRef' => $node->byRef,
? ? ? ? ? ? ? ? 'params' => $node->params,
? ? ? ? ? ? ? ? 'returnType' => $returnType,
? ? ? ? ? ? ? ? 'stmts' => $stmts,
? ? ? ? ? ? ]);
? ? ? ? }
? ? }
? ? public function afterTraverse(array $nodes)
? ? {
? ? ? ? $addEnhancementMethods = true;
? ? ? ? $nodeFinder = new NodeFinder();
? ? ? ? $nodeFinder->find($nodes, function (Node $node) use (
? ? ? ? ? ? &$addEnhancementMethods
? ? ? ? ) {
? ? ? ? ? ? if ($node instanceof TraitUse) {
? ? ? ? ? ? ? ? foreach ($node->traits as $trait) {
? ? ? ? ? ? ? ? ? ? // Did AopTrait trait use ?
? ? ? ? ? ? ? ? ? ? if ($trait instanceof Name && $trait->toString() === '\App\Aop\AopTrait') {
? ? ? ? ? ? ? ? ? ? ? ? $addEnhancementMethods = false;
? ? ? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? // Find Class Node and then Add Aop Enhancement Methods nodes and getOriginalClassName() method
? ? ? ? $classNode = $nodeFinder->findFirstInstanceOf($nodes, Class_::class);
? ? ? ? $addEnhancementMethods && array_unshift($classNode->stmts, $this->getAopTraitUseNode());
? ? ? ? return $nodes;
? ? }
}
trait AopTrait
{
? ? /**
? ? ?* AOP proxy call method
? ? ?*
? ? ?* @param \Closure $closure
? ? ?* @param string ? $method
? ? ?* @param array ? ?$params
? ? ?* @return mixed|null
? ? ?* @throws \Throwable
? ? ?*/
? ? public function __proxyCall(\Closure $closure, string $method, array $params)
? ? {
? ? ? ? return $closure(...$params);
? ? }
}

當(dāng)我們拿到節(jié)點(diǎn)是類時(shí),我們重置這個(gè)類,讓新建的類繼承這個(gè)類。

當(dāng)我們拿到的節(jié)點(diǎn)是類方法時(shí),我們使用 proxyCall 來重寫方法。

當(dāng)遍歷完成之后,給類加上我們定義好的 AopTrait。

執(zhí)行

接下來,讓我們執(zhí)行以下第二個(gè) DEMO

use PhpParser\ParserFactory;
use PhpParser\NodeTraverser;
use App\Aop\ProxyVisitor;
use PhpParser\PrettyPrinter\Standard;
$file = APP_PATH . '/Test.php';
$code = file_get_contents($file);
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse($code);
$traverser = new NodeTraverser();
$className = 'App\\Test';
$proxyId = uniqid();
$visitor = new ProxyVisitor($className, $proxyId);
$traverser->addVisitor($visitor);
$proxyAst = $traverser->traverse($ast);
if (!$proxyAst) {
? ? throw new \Exception(sprintf('Class %s AST optimize failure', $className));
}
$printer = new Standard();
$proxyCode = $printer->prettyPrint($proxyAst);
echo $proxyCode;

結(jié)果如下

namespace App;
class Test_5b495d7565933 extends \App\Test
{
? ? use \App\Aop\AopTrait;
? ? public function show()
? ? {
? ? ? ? return $this->__proxyCall(function () {
? ? ? ? ? ? return 'hello world';
? ? ? ? }, 'show', func_get_args());
? ? }
}

這樣就很有趣了,我們可以賦予新建的類一個(gè)新的方法,比如 getOriginClassName。然后我們在 proxyCall 中,就可以根據(jù) getOriginClassName 和 $method 拿到方法的精確 ID,在這基礎(chǔ)之上,我們可以做很多東西,比如實(shí)現(xiàn)一個(gè)方法緩存。

我這里呢,只給出一個(gè)最簡單的示例,就是當(dāng)返回值為 string 的時(shí)候,加上個(gè)嘆號(hào)。

修改一下我們的代碼

namespace App\Aop;
trait AopTrait
{
? ? /**
? ? ?* AOP proxy call method
? ? ?*
? ? ?* @param \Closure $closure
? ? ?* @param string ? $method
? ? ?* @param array ? ?$params
? ? ?* @return mixed|null
? ? ?* @throws \Throwable
? ? ?*/
? ? public function __proxyCall(\Closure $closure, string $method, array $params)
? ? {
? ? ? ? $res = $closure(...$params);
? ? ? ? if (is_string($res)) {
? ? ? ? ? ? $res .= '!';
? ? ? ? }
? ? ? ? return $res;
? ? }
}

以及在我們的調(diào)用代碼后面加上以下代碼

eval($proxyCode);
$class = $visitor->getClassName();
$bean = new $class();
echo $bean->show();

結(jié)果當(dāng)然和我們預(yù)想的那樣,打印出了

hello world!

以上設(shè)計(jì)來自 Swoft 開發(fā)組 swoft-component,我只是個(gè)懶惰的搬運(yùn)工,有興趣的可以去看一下。

以上就是PHP parser重寫PHP類使用示例詳解的詳細(xì)內(nèi)容,更多關(guān)于PHP parser重寫PHP類的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 用 Composer構(gòu)建自己的 PHP 框架之基礎(chǔ)準(zhǔn)備

    用 Composer構(gòu)建自己的 PHP 框架之基礎(chǔ)準(zhǔn)備

    這篇文章主要介紹了用 Composer構(gòu)建自己的 PHP 框架的基礎(chǔ)準(zhǔn)備工作,其實(shí)就是各種基礎(chǔ)知識(shí),想自己搭建php框架的童鞋可要看仔細(xì)了
    2014-10-10
  • php+ajax注冊實(shí)時(shí)驗(yàn)證功能

    php+ajax注冊實(shí)時(shí)驗(yàn)證功能

    我們在網(wǎng)站上面注冊時(shí),在輸入用戶名時(shí),首先要進(jìn)行無刷新驗(yàn)證,這篇文章主要為大家詳細(xì)介紹了php+ajax注冊實(shí)時(shí)驗(yàn)證功能,感興趣的小伙伴們可以參考一下
    2016-07-07
  • thinkphp視圖模型查詢提示ERR: 1146:Table ''db.pr_order_view'' doesn''t exist的解決方法

    thinkphp視圖模型查詢提示ERR: 1146:Table ''db.pr_order_view'' doesn''

    這篇文章主要介紹了thinkphp視圖模型查詢提示ERR: 1146:Table 'db.pr_order_view' doesn't exist的解決方法,對(duì)于ThinkPHP初學(xué)者來說有一定的借鑒價(jià)值,需要的朋友可以參考下
    2014-10-10
  • php讀取qqwry.dat ip地址定位文件的類實(shí)例代碼

    php讀取qqwry.dat ip地址定位文件的類實(shí)例代碼

    下面小編就為大家?guī)硪黄猵hp讀取qqwry.dat ip地址定位文件的類實(shí)例代碼。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-11-11
  • Laravel創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu)的例子

    Laravel創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu)的例子

    今天小編就為大家分享一篇Laravel創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu)的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-10-10
  • Thinkphp 空操作、空控制器、命名空間(詳解)

    Thinkphp 空操作、空控制器、命名空間(詳解)

    下面小編就為大家?guī)硪黄猅hinkphp 空操作、空控制器、命名空間(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-05-05
  • PHP對(duì)稱加密函數(shù)實(shí)現(xiàn)數(shù)據(jù)的加密解密

    PHP對(duì)稱加密函數(shù)實(shí)現(xiàn)數(shù)據(jù)的加密解密

    本文詳細(xì)介紹了PHP一個(gè)簡單的對(duì)稱加密函數(shù)實(shí)現(xiàn)數(shù)據(jù)的加密解密,詳細(xì)的介紹了對(duì)稱加密和非對(duì)稱加密,有需要的可以了解一下。
    2016-10-10
  • PHPMYADMIN 簡明安裝教程 推薦

    PHPMYADMIN 簡明安裝教程 推薦

    簡單的說,phpmyadmin就是一種mysql的管理工具,安裝該工具后,即可以通過web形式直接管理mysql數(shù)據(jù),而不需要通過執(zhí)行系統(tǒng)命令來管理,非常適合對(duì)數(shù)據(jù)庫操作命令不熟悉的數(shù)據(jù)庫管理者,下面我就說下怎么安裝該工具
    2010-03-03
  • php記錄搜索引擎爬行記錄的實(shí)現(xiàn)代碼

    php記錄搜索引擎爬行記錄的實(shí)現(xiàn)代碼

    這篇文章主要介紹了php記錄搜索引擎爬行記錄的實(shí)現(xiàn)代碼,然后在文中給大家補(bǔ)充介紹了php獲取各搜索蜘蛛爬行記錄的代碼,需要的朋友可以參考下
    2018-03-03
  • TP5框架實(shí)現(xiàn)簽到功能的方法分析

    TP5框架實(shí)現(xiàn)簽到功能的方法分析

    這篇文章主要介紹了TP5框架實(shí)現(xiàn)簽到功能的方法,結(jié)合實(shí)例形式分析了TP5框架實(shí)現(xiàn)簽到功能相關(guān)數(shù)據(jù)表建立、以及數(shù)據(jù)的查詢、判斷、寫入等相關(guān)操作技巧,需要的朋友可以參考下
    2020-04-04

最新評(píng)論

方正县| 和静县| 隆回县| 东宁县| 桐庐县| 新晃| 正安县| 康马县| 黔西| 临潭县| 搜索| 板桥市| 安阳县| 光泽县| 原阳县| 晋宁县| 四平市| 通化县| 广昌县| 绵阳市| 图木舒克市| 始兴县| 榆社县| 图片| 大城县| 天峻县| 鲜城| 屯昌县| 佳木斯市| 莱芜市| 临沭县| 洛宁县| 洮南市| 古蔺县| 钟山县| 涪陵区| 尉氏县| 宜宾市| 乌拉特后旗| 应用必备| 长顺县|