feat : Decorator Aop

This commit is contained in:
2025-09-06 23:53:15 +08:00
parent aaa394a2a7
commit dfbb4b73ae
9 changed files with 195 additions and 9 deletions

View File

@@ -0,0 +1,54 @@
<?php
namespace App\Aspect\Test\Decorator\Aop;
use App\Service\Test\Decorator\Aop\UserService;
use Hyperf\Cache\Cache;
use Hyperf\Context\ApplicationContext;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Di\Exception\Exception;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\SimpleCache\InvalidArgumentException;
/**
* 切入类 属性值 priority 数字越大优先级越高 提前返回的CacheableAspect类必须要在后面
*/
#[Aspect(priority: 1)]
class CacheableAspect extends AbstractAspect
{
/**
* 切入接口类
* @var array|string[]
*/
public array $classes = [
UserService::class . '::getUserInfo',
];
/**
* @param ProceedingJoinPoint $proceedingJoinPoint
* @return mixed
* @throws Exception
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws InvalidArgumentException
*/
public function process(ProceedingJoinPoint $proceedingJoinPoint): mixed
{
$userId = $proceedingJoinPoint->arguments['keys']['userId'];
print_r('切入cache数据:'.json_encode($proceedingJoinPoint->arguments));
$cacheKey = 'list:userInfo:' . $userId;
$cache = ApplicationContext::getContainer()->get(Cache::class);
if ($cache->has($cacheKey)) return $cache->get($cacheKey);
$result = $proceedingJoinPoint->process();
$cache->set($cacheKey, $result, 3600);
return $result;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace App\Aspect\Test\Decorator\Aop;
use App\Interface\Test\Decorator\LoggerInterface;
use App\Service\Test\Decorator\Aop\UserService;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Di\Exception\Exception;
#[Aspect(priority: 2)]
class LoggableAspect extends AbstractAspect
{
/**
* 切入接口类
* @var array|string[]
*/
public array $classes = [
UserService::class . '::getUserInfo',
];
/**
* @var LoggerInterface
*/
#[Inject]
protected LoggerInterface $logger;
/**
* @param ProceedingJoinPoint $proceedingJoinPoint
* @return mixed
* @throws Exception
*/
public function process(ProceedingJoinPoint $proceedingJoinPoint): mixed
{
$userId = $proceedingJoinPoint->arguments['keys']['userId'];
// $logger = ApplicationContext::getContainer()->get(LoggerFactory::class)->get('app');
print_r('切入logger数据:'.json_encode($proceedingJoinPoint->arguments));
$this->logger->debug('调用前获取用户信息的ID' . $userId);
$result = $proceedingJoinPoint->process();
$this->logger->debug('调用后检索用户信息的ID' . $userId);
return $result;
}
}