hyperf中间件全局更改请求对象
                                                                
                19-08-06 20:22
                字数 138
                阅读 6090
                                已编辑
                                            
            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人点赞>
                    请登录后发表评论
        
        相关推荐
        
    文章归档
    
最新文章
        最受欢迎
    05-14 12:45
                    24-10-30 12:05
                    23-09-27 17:00
                    23-09-03 10:57
                    3 评论
                    3 评论
                    2 评论
                    
    
    
更新了文章排版