一、创建中间件:
所有的中间件都会被默认创建到app/Middlware目录下
php bin/hyperf.php gen:middleware Auth/UserTokenMiddleware
$ php bin/hyperf.php gen:middleware Auth/UserTokenMiddleware [DEBUG] [command] Commands registered by Hyperf\Command\Listener\RegisterCommandListener [DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Command\Listener\RegisterCommandListener listener. [DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener. [DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\DbConnection\Listener\RegisterConnectionResolverListener listener. [DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\ExceptionHandler\Listener\ExceptionHandlerListener listener. [DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\ExceptionHandler\Listener\ErrorExceptionHandler listener. App\Middleware\Auth\UserTokenMiddleware created successfully.

二、中间件的使用
1、定义全局中间件:在config/autoload/middlewares.php下定义
return [ 'http' => [ App\Middleware\Auth\UserTokenMiddleware::class, ], ];
2、定义局部中间件
2.1、在路由里定义:在config/routes.php
Router::addRoute(['GET', 'POST', 'HEAD'], '/test', 'App\Controller\IndexController@test', ['middleware' => [ \App\Middleware\Auth\UserTokenMiddleware::class ] ]);
2.2、在控制器里定义:当路由的定时方式是注解的时候才可以实现
#[Middlewares]:定义多个中间件,用{}包裹
#[Middleware]:定义单个中间件
使用 #[Middleware] 注解时需 use Hyperf\HttpServer\Annotation\Middleware; 命名空间;
使用 #[Middlewares] 注解时需 use Hyperf\HttpServer\Annotation\Middlewares; 命名空间;
注意:必须配合 #[AutoController] 或者 #[Controller] 使用
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
#[Controller(prefix: 'user')]
#[Middleware(\App\Middleware\Auth\UserTokenMiddleware::class)]
//#[Middlewares([FooMiddleware::class, BarMiddleware::class])]
class ClientController extends AbstractController
{
#[RequestMapping(path: 'index', methods: 'get')]
public function index()
{
$user = $this->request->input('user', 'Hyperf');
$method = $this->request->getMethod();
return [
'method' => $method,
'message' => "Hello {$user}.",
];
}
} 定义方法级别中间件
只需将注解直接定义到方法上即可。类级别上的中间件会优先于方法级别的中间件,我们通过代码来举例一下:
<?php
namespace App\Controller;
use App\Middleware\BarMiddleware;
use App\Middleware\FooMiddleware;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
#[AutoController]
#[Middlewares([FooMiddleware::class])]
class IndexController
{
#[Middleware(BarMiddleware::class)]
public function index()
{
return 'Hello Hyperf.';
}
}多个中间件的执行顺序:全局中间件→类级别中间件→方法级别中间件
三、中间件的内容的编写
<?php
declare(strict_types=1);
namespace App\Middleware\Auth;
use Hyperf\HttpServer\Contract\RequestInterface as Request;
use Hyperf\HttpServer\Contract\ResponseInterface as Response;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class UserTokenMiddleware implements MiddlewareInterface
{
protected $container;
protected $response;
protected $request;
public function __construct(ContainerInterface $container, Response $response, Request $request)
{
$this->container = $container;
$this->response = $response;
$this->request = $request;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
//return $handler->handle($request);
// token验证
$checkToken = false;
if ($checkToken) { // 验证成功继续往下请求
return $handler->handle($request);
} else { // 验证失败直接返回json内容
return $this->response->json(
[
'code' => -1,
'data' => [
'error' => '中间里验证token无效,阻止继续向下执行',
],
]
);
}
}
}
本文为崔凯原创文章,转载无需和我联系,但请注明来自冷暖自知一抹茶ckhttp://www.cksite.cn