hyperf 中间件 - 胡勇健 - D1h.Net第一号博客
返回主页

胡勇健

hyperf 中间件

控制器 app/Controller/IndexController.php

<?php namespace App\Controller; use Hyperf\HttpServer\Annotation\AutoController; class IndexController { public function middleware(){ return 'middle-ware'; } }

中间件1 app/Middleware/Middleware1.php

<?php declare(strict_types=1); namespace App\Middleware; 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 Middleware1 implements MiddlewareInterface { /** * @var ContainerInterface */ protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { echo 'middleware1'.PHP_EOL; return $handler->handle($request); } }

中间件2 app/Middleware/Middleware2.php

<?php declare(strict_types=1); namespace App\Middleware; 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 Middleware2 implements MiddlewareInterface { /** * @var ContainerInterface */ protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { echo "middleware2".PHP_EOL; return $handler->handle($request); } }

添加路由 config/routes.php

Router::get('/middleware', [\App\Controller\IndexController::class, 'middleware'], ['middleware' => [Middleware1::class,Middleware2::class]]);

客户端访问测试

curl 118.195.173.53:9501/middleware

客户端显示

middle-ware

服务端显示

middleware1 middleware2
posted @ 2021-09-16 16:14  胡勇健  阅读(7)  评论(0编辑  收藏  举报
Copyright © 2021 胡勇健
Powered by .NET 6 on Kubernetes

问答 28u iTmz.Net 3q科技 A8团队1 A8团队2 A8团队3 A8备