AOP

感谢 Hyperf 作者的提交

安装

  • 安装 aop-integration
  1. composer require "hyperf/aop-integration: ^1.1"

增加 AOP 相关配置

我们需要在 config 目录下,增加 config.php 配置

  1. <?php
  2. use Hyperf\Di\Annotation\AspectCollector;
  3. return [
  4. 'annotations' => [
  5. 'scan' => [
  6. 'paths' => [
  7. BASE_PATH . '/app',
  8. ],
  9. 'ignore_annotations' => [
  10. 'mixin',
  11. ],
  12. 'class_map' => [
  13. ],
  14. 'collectors' => [
  15. AspectCollector::class
  16. ],
  17. ],
  18. ],
  19. 'aspects' => [
  20. // 这里写入对应的 Aspect
  21. app\aspect\DebugAspect::class,
  22. ]
  23. ];

配置入口文件 start.php

我们将初始化方法,放到 timezone 下方,以下省略其他代码

  1. use Hyperf\AopIntegration\ClassLoader;
  2. if ($timezone = config('app.default_timezone')) {
  3. date_default_timezone_set($timezone);
  4. }
  5. // 初始化
  6. ClassLoader::init();

测试

首先让我们编写待切入类

  1. <?php
  2. namespace app\service;
  3. class UserService
  4. {
  5. public function first(): array
  6. {
  7. return ['id' => 1];
  8. }
  9. }

其次新增对应的 DebugAspect

  1. <?php
  2. namespace app\aspect;
  3. use app\service\UserService;
  4. use Hyperf\Di\Aop\AbstractAspect;
  5. use Hyperf\Di\Aop\ProceedingJoinPoint;
  6. class DebugAspect extends AbstractAspect
  7. {
  8. public $classes = [
  9. UserService::class . '::first',
  10. ];
  11. public function process(ProceedingJoinPoint $proceedingJoinPoint)
  12. {
  13. var_dump(11);
  14. return $proceedingJoinPoint->process();
  15. }
  16. }

接下来编辑控制器 app\controller\Index

  1. <?php
  2. namespace app\controller;
  3. use app\service\UserService;
  4. use support\Request;
  5. class Index
  6. {
  7. public function json(Request $request)
  8. {
  9. return json(['code' => 0, 'msg' => 'ok', 'data' => (new UserService())->first()]);
  10. }
  11. }

然后配置路由

  1. <?php
  2. use Webman\Route;
  3. Route::any('/json', [app\controller\Index::class, 'json']);

最后启动服务,并测试。

  1. php start.php start
  2. curl http://127.0.0.1:8787/json