我应该如何在中间件和控制器之间传递数据?

How should I pass data between middlewares and controllers?

我想就传递数据的最佳做法提出一些意见 to/from 控制器和中间件 - 请记住,中间件可以是 'before' 或 'after'。

过去,我对请求进行了更改并合并了输入。但是,这次我需要 'after' 中间件的解决方案。所以我宁愿在控制器有 运行.

之后不依赖于请求

我的具体情况 - 是我的控制器 returns 一个普通的视图响应,我的中间件将它 运行 压缩成一个 pdf。所以我需要在控制器和after中间件中加载文件配置。纸张配置从模板更改为模板。

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

<?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 会说 'letter' 和 'landscape' 之类的内容。发出去完全没问题,或许发出去也合适。