【问题标题】:How should I pass data between middlewares and controllers?我应该如何在中间件和控制器之间传递数据?
【发布时间】:2019-02-23 17:46:41
【问题描述】:

我想对将数据传入/传出控制器和中间件的最佳做法提出一些意见 - 请记住,中间件可以是“之前”或“之后”。

过去,我对请求和合并输入进行了更改。但是,这一次我需要一个“后”中间件的解决方案。所以我宁愿在控制器运行后不依赖请求。

我的具体情况是我的控制器返回一个正常的视图响应,而我的中间件将它压缩成 pdf。所以我需要在控制器以及 after 中间件中加载纸张配置。纸张配置从模板更改为模板。

我想在控制器中加载纸质配置,然后...“返回”到以某种方式隐藏在响应中的中间件。

【问题讨论】:

    标签: laravel middleware laravel-middleware


    【解决方案1】:
    <?php
    namespace FuquIo\LaravelPdfMaker;
    use Illuminate\Http\Request;
    use Closure;
    
    class Middleware{
    
        public function handle(Request $request, Closure $next){
    
            /**
            * This is the only way I have found to change
            * inputs without breaking request validation.
            */
            $inputs = $request->request->all();
            $inputs['data_for_controller'] = 'foo bar';
            $request->replace($inputs);
    
            // run controller
            $response = $next($request);
    
            //...do something based on x-controller-info...
            $headers = collect($response->headers->all())->only(['x-data-from-controller']);
            //...
    
            return $response;
        }
    }
    

    TheController.php

    public function theAction(MyValidRequest $request){
        $from_middleware = $request->data_for_controller;
        return response()         
            ->view('myBladeView', ['display_data' => $from_middleware])
            ->header('x-data-from-controller', 'insecure string for middleware');
    
    }
    

    x-headers 将显示 应该使用这个 x-header 东西的情况并不多。它会进入浏览器,所以它完全不安全。在我的实际用例中,中间件正在制作 pdf,所以 x-headers 会说“字母”和“风景”之类的东西。发送出去完全没问题,甚至可能适合发送出去。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多