国产+高潮+在线,国产 av 仑乱内谢,www国产亚洲精品久久,51国产偷自视频区视频,成人午夜精品网站在线观看

Aop 切面編程

0.1.2 版本
2024-09-02 版本更新時(shí)間
22 安裝
9 star

?。。?不能生產(chǎn)使用,僅作為研究用途

一款簡單Aop實(shí)現(xiàn)。支持常駐內(nèi)存型PHP應(yīng)用??梢苑奖憬尤隢extPHP, Swoole,WebMan等框架。

環(huán)境要求

php >=8.2 with passthru function enabled

安裝

composer require next/aop

使用,以下以webman為例

修改start.php文件

Aop::init(
    [__DIR__ . '/app'],
    [
        \Next\Aop\Collector\AspectCollector::class,
        \Next\Aop\Collector\PropertyAttributeCollector::class,
    ],
    __DIR__ . '/runtime/aop',
);
  • paths 注解掃描路徑
  • collectors 注解收集器
    • \Next\Aop\Collector\AspectCollector::class 切面收集器,取消后不能使用切面
    • \Next\Aop\Collector\PropertyAttributeCollector::class 屬性注解收集器,取消后不支持屬性自動注入
  • runtimeDir 運(yùn)行時(shí),生成的代理類和代理類地圖會被緩存到這里

編寫切面類,實(shí)現(xiàn)AspectInterface接口

<?php

namespace App\aspects;

use Closure;
use Next\Aop\JoinPoint;
use Next\Aop\Contract\AspectInterface;

#[\Attribute(\Attribute::TARGET_METHOD)]
class Round implements AspectInterface
{
    public function process(JoinPoint $joinPoint, Closure $next): mixed
    {
        echo 'before';
        $result = $next($joinPoint);
        echo 'after';
        return $result;
    }
}

修改方法添加切面注解

<?php

namespace app\controller;

use App\aspects\Round;
use Next\Di\Attribute\Inject;
use support\Request;

class Index
{
    #[Inject]
    protected Request $request;

    #[Round]
    public function index()
    {
        echo '--controller--';
        return response('hello webman');
    }
}

注意上面添加了兩個(gè)注解,屬性和方法注解的作用分別為注入屬性和切入方法,可以直接在控制器中打印屬性$request發(fā)現(xiàn)已經(jīng)被注入了,切面注解可以有多個(gè),會按照順序執(zhí)行。具體實(shí)現(xiàn)可以參考這兩個(gè)類,注意這里的Inject注解并不是從webman容器中獲取實(shí)例,所以使用的話需要重新定義Inject以保證單例

你也可以使用AspectConfig注解類配置要切入的類,例如上面的切面類

<?php

namespace App\aspects;

use Closure;
use Next\Aop\Attribute\AspectConfig;
use Next\Aop\JoinPoint;
use Next\Aop\Contract\AspectInterface;

#[\Attribute(\Attribute::TARGET_METHOD)]
#[AspectConfig('BaconQrCode\Writer', 'writeFile')]
class Round implements AspectInterface
{
    public function process(JoinPoint $joinPoint, Closure $next): mixed
    {
        echo 'before';
        $result = $next($joinPoint);
        echo 'after';
        return $result;
    }
}

那么BaconQrCode\Writer類的writeFile方法將會被切入,該注解可以傳遞第三個(gè)參數(shù)數(shù)組,作為該切面構(gòu)造函數(shù)的參數(shù)

啟動

php start.php start

打開瀏覽器打開對應(yīng)頁面

控制臺輸出內(nèi)容為

before--controller--after
贊助商