当前位置:   article > 正文

Hyperf自定义注解,aop切面实现接口参数校验_hyperf 切面

hyperf 切面

1.自定义注解

<?php

namespace App\Annotation;


use Hyperf\Di\Annotation\AbstractAnnotation;

/**
 * @Annotation
 * @Target({"CLASS","METHOD"}) #CLASS 参考问档
 */
class ValidateParams extends AbstractAnnotation
{


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

2.创建aop切面

<?php

namespace App\Aspect;

use App\Annotation\ValidateParams;
use App\common\response\SystemCode;
use App\Exception\ValidateException;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Logger\LoggerFactory;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Psr\Container\ContainerInterface;


/**
 * @Aspect
 */
class ValidateAspect extends AbstractAspect
{

    protected $container;

    protected $request;

    protected $logger;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    public function __construct(ContainerInterface $container, RequestInterface $request, LoggerFactory $logger)
    {
        $this->container = $container;
        $this->request = $request;
        $this->logger = $logger->get('log', 'default');
    }

    // 要切入的类或 Trait,可以多个,亦可通过 :: 标识到具体的某个方法,通过 * 可以模糊匹配
    /*public $classes = [
        'App\Controller\TestController::*Method',
    ];*/

    // 要切入的注解,具体切入的还是使用了这些注解的类,仅可切入类注解和类方法注解
    public $annotations = [
        ValidateParams::class,
    ];

    /**
     * @inheritDoc
     */
    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        // 在调用前进行某些处理
        $this->logger->info(date('Y-m-d H:i:s', time()),["ValidateParams注解调用前执行..."]);
        //获取控制器和方法
        list($LongController, $method) = $this->request->getAttribute(Dispatched::class)->handler->callback;
        $controller = substr(substr(strrchr($LongController,'\\'),1),0,-10);
        $res = $this->paramsValidate($controller,$method,$this->request);
        if($res["code"] === -1){
            //return RespResult::result(SystemCode::SYSTEM_ERROR_PARAM_NULL,$res["data"],[]);//方式1
            throw new ValidateException($res["data"],SystemCode::SYSTEM_ERROR_PARAM_NULL);//方式2
        }

        $result = $proceedingJoinPoint->process();

        // 在调用后进行某些处理
        $this->logger->info(date('Y-m-d H:i:s', time()),["ValidateParams注解调用后执行..."]);
        return $result;
    }


    /**
     * 参数校验函数
     * @param $controller
     * @param $method
     * @param $request
     * @return array
     */
    private function paramsValidate($controller,$method,$request){
        $nameSpace = '\App\Vilidate\\'.$controller;
        $ValidateObj = (new $nameSpace)->$method;
        $validator = $this->validationFactory->make(
            $request->all(),$ValidateObj["rule"],$ValidateObj["msg"]
        );
        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            return ["code"=>-1,"msg"=>"校验不通过!","data"=>$errorMessage];
        }
        //校验通过
        return ["code"=>0,"msg"=>"校验通过!","data"=>[]];
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99

3.添加校验规则

<?php

namespace App\Vilidate;

/**
 * test控制器下的验证规则类
 */
class Test
{

    public $index = [
        'rule'=>[
        ],
        'msg'=>[
        ]
    ];


    public $exceptionTest = [
        'rule'=>[
            'title' => 'required|max:5',
            'body' => 'required',
        ],
        'msg'=>[
            'title.required' => 'title参数不能为空!',
            'title.max' => 'title最大长度超限',
            'body.required' => 'body参数不能为空!',
        ]
    ];



    public $eventTest = [
        'rule'=>[
            'title' => 'required|max:5',
            'body' => 'required',
        ],
        'msg'=>[
            'title.required' => 'title参数不能为空!',
            'title.max' => 'title最大长度超限',
            'body.required' => 'body参数不能为空!',
        ]
    ];

    public $getUser = [
        'rule'=>[
            'userId' => 'required|min:0|numeric',
        ],
        'msg'=>[
            'userId.required' => 'userId参数不能为空!',
            'userId.numeric' => 'userId格式必须为数字!',
            'userId.min' => 'userId最小长度超限',
        ]
    ];

    public $validateTest = [
        'rule'=>[
            'userId' => 'required|min:0|numeric',
        ],
        'msg'=>[
            'userId.required' => 'userId参数不能为空!',
            'userId.numeric' => 'userId格式必须为数字!',
            'userId.min' => 'userId最小长度超限',
        ]
    ];


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68

4.使用

/**
     * @RequestMapping(path="/validateTest", methods="get,post")
     * @ValidateParams
     * @param RequestInterface $request
     * @return array
     */
    public function validateTest(RequestInterface $request)
    {
        $params = $request->all();
        $userId = $params["userId"];
        return RespResult::result(SystemCode::SYSTEM_SUCCESS, SystemMessage::SYSTEM_SUCCESS, $this->userModel->getUser($userId));
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

5.检验是否可以拦截

在这里插入图片描述

注:用到的注解,一定要use引进来哈

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/548757
推荐阅读
相关标签
  

闽ICP备14008679号