我想对从控制器和中间件传递数据的最佳实践有一些看法 - 请记住,中间件可以在“之前”或“之后”。
过去,我已对请求进行了更改并合并了输入。但是,这次我需要一个'后'中间件的解决方案。所以我只是在控制器运行后不依赖于请求。
我的具体情况是 - 我的控制器返回正常的视图响应,我的中间件将其压缩为pdf。所以我需要在控制器和后中间件中加载纸张配置。纸张配置从模板更改为模板。
我想在控制器中加载纸张配置,然后......将其返回到以某种方式隐藏在响应中的中间件。
<?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-header没有太多的情况应该使用这个x-header的东西。它会去浏览器,所以它完全不安全。在我的实际用例中,中间件正在制作pdf,因此x-headers会说'letter'和'landscape'之类的东西。将它发送出去完全没问题,甚至可能适合发送出去。