hyperf中间件全局更改请求对象

19-08-06 20:22 字数 138 阅读 5176 已编辑

hyperf文档:https://doc.hyperf.io

1. 生成中间件和控制器

php bin/hyperf.php gen:middleware TestMiddleware
php bin/hyperf.php gen:controller TestController

2. 定义中间件

<?php
declare(strict_types=1);

namespace App\Middleware;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\Context;
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 TestMiddleware implements MiddlewareInterface
 {
     /**
      * @var ContainerInterface
      */
     protected $container;

     /**
      * @var RequestInterface
      */
     protected $request;

     /**
      * @var HttpResponse
      */
     protected $response;

     public function __construct(ContainerInterface $container, RequestInterface $request, HttpResponse $response)
     {
        $this->container = $container;
        $this->request = $request;
        $this->response = $response;
     }

     public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
     {
        // 将新的请求对象设置到上下文中
        $request = $request->withAttribute('name', 'danton');
        Context::set(ServerRequestInterface::class, $request);
        return $handler->handle($request);
     }
 }

3. 定义控制器

<?php
 declare(strict_types=1);

 namespace App\Controller;

 use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Middleware\TestMiddleware;
use Hyperf\Utils\Context;
use Psr\Http\Message\ServerRequestInterface;

 /**
    * Class TestController
    * @package App\Controller
    * @\Hyperf\HttpServer\Annotation\Controller()
    */
class TestController extends Controller
{
     /**
      * @RequestMapping(path="/test", methods="get, post")
      * @Middleware(TestMiddleware::class)
      */
     public function test()
     {
        // 获取上下文中的所有属性,指定属性使用getAttribute('name')
        return $this->request->getAttributes();

        // 效果同上
        return Context::get(ServerRequestInterface::class)->getAttributes();
     }
}

4. 启动http服务

php bin/hyperf.php start
curl 127.0.0.1:9508/test   // {"name":"danton"}
2人点赞>
关注 收藏 改进 举报
1 条评论
排序方式 时间 投票
Up骚年

更新了文章排版

请登录后发表评论