1.引入组件包
composer require hyperf/validation
2.创建中间件:php ./bin/hyperf.php gen:middleware ValidateMiddleware
3.编写接口验证中间件(ValidateMiddleware.php):App\Middleware\ValidateMiddleware::class
<?php
declare(strict_types=1);
namespace App\Middleware;
use App\common\response\RespResult;
use App\common\response\SystemCode;
use App\Exception\ValidateException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\HttpServer\Router\Handler;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
class ValidateMiddleware implements MiddlewareInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var HttpResponse
*/
protected $response;
/**
* @var RequestInterface
*/
protected $request;
/**
* @Inject()
* @var ValidatorFactoryInterface
*/
protected $validationFactory;
public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
{
$this->container = $container;
$this->response = $response;
$this->request = $request;
}
/**
* 业务逻辑处理
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
//获取控制器和方法
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
}
return $handler->handle($request);
}
/**
* 参数校验函数
* @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"=>[]];
}
}
4.定义全局中间件,所有接口都会执行此中间件(middlewares.php),如果是定义局部中间件这里不需要进行配置
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
//全局中间件配置在该文件及对应的 Server Name 内,即该 Server 下的所有请求都会应用配置的全局中间件。
return [
'http' => [
\App\Middleware\ValidateMiddleware::class,
],
];
5.接口参数中的验证以及消息设置(验证组件:hyperf/validation是借鉴了laravel的illuminate/validation,所以两者使用方式基本一致),我们将这块逻辑放在App\Vilidate下,以test控制器为例,在Vilidate文件夹下创建test.php
<?php
namespace App\Vilidate;
/**
* test控制器下的验证规则类
*/
class Test
{
public $exceptionTest = [
'rule'=>[
'title' => 'required|max:5',
'body' => 'required',
],
'msg'=>[
'title.required' => 'title参数不能为空!',
'title.max' => 'title最大长度超限',
'body.required' => 'body参数不能为空!',
]
];
}
6.使用方法(采用的注解方式访问和加载中间件)
/**
* 异常处理测试
* @RequestMapping(path="exceptionTest", methods="get,post")
* @Middleware(ValidateMiddleware::class)
*/
public function exceptionTest(){
/*if(true){
throw new ValidateException();
}*/
return RespResult::success();
}
7.效果