[pandaman] 简单一步,即可实现对任意方法的无侵入增强

wasoncheung

继今天发布通过固定注解来包装的切面后,发现在实际业务中局限性还是很大,于是又继续完善了下。采用接口的形式进行定义处理。而不是固定的通过包装的形式。 你可以把这个想成“针对某个方法的”中间件调用链

实现接口

<?php

declare(strict_types=1);

namespace app\admin\attribute;

use panda\container\Contract\AopHandlerInterface;
use ReflectionFunction;
use ReflectionMethod;

#[\Attribute(\Attribute::TARGET_METHOD)]
class PermissionCheck implements AopHandlerInterface
{
    public function beforeEntering(ReflectionMethod|ReflectionFunction $reflect, array $serviceVariables): mixed
    {
       dump('前置处理');
       return null;
    }

    public function afterComingOut(ReflectionMethod|ReflectionFunction $reflect, mixed $serviceResult): void
    {
        dump('后置处理');
    }
}

调用

class Test
{
    #[RequestMapping('/demo')]
    // 进入控制器前 进行权限认证
    // 控制器执行完毕后 日志记录 等等 实现业务的无侵入增强
    #[PermissionCheck]
    public function index(Cache $cache): string
    {
       dump('hello world');
        return 'hello world';
    }
}
525 0 0
0个评论

wasoncheung

1070
积分
0
获赞数
0
粉丝数
2022-11-15 加入
🔝