在中间件上调用terminate方法时,Laravel将从服务容器中解析新的中间件实例。如果您想在调用handle和terminate方法时使用相同的中间件实例,请使用容器的singleton方法向容器注册中间件。
真诚的我从未做过这样的事情,但你需要的是将你的中间件注册为singleton。从Laravel service container documentation我明白,这可以通过这样的方式完成
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('HelpSpot\API', function ($app) {
return new HelpSpot\API($app->make('HttpClient'));
});
}
}
但是,为了在运行时注册中间件,你必须做这样的事情
$this->app['router']->middleware('middleware_name', App\Middleware\Name::class);
如果您了解如何将这两种方法合并在一起,请告诉我。