应用中间件后,服务提供商中的访问请求 [英] Access Request in Service Provider After Applying Middleware
本文介绍了应用中间件后,服务提供商中的访问请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在服务提供者中使用接口和实现之间的绑定:
I'm using bindings in my service provider between interface and implementation:
public function register()
{
$this->app->bind('MyInterface', MyImplementation::class);
}
中间件
在我的中间件中,我向请求添加了一个属性:
Middleware
In my middleware, I add an attribute to the request:
public function handle($request, Closure $next)
{
$request->attributes->add(['foo' => 'bar]);
return $next($request);
}
现在,我要访问服务提供商中的foo
public function register()
{
$this->app->bind('MyInterface', new MyImplementation($this->request->attributes->get('foo')); // Request is not available
}
在应用中间件之前调用register().我知道.
如果要设置request-> attributes-> get('foo'),我正在寻找一种重新绑定"的技术
The register() is called before applying the middleware. I know.
I'm looking for a technique to 'rebind' if the request->attributes->get('foo') is set
推荐答案
尝试如下:
public function register()
{
$this->app->bind('MyInterface', function () {
$request = app(\Illuminate\Http\Request::class);
return app(MyImplementation::class, [$request->foo]);
}
}
绑定元素的工作方式如下,只有在调用它们时才会触发它们.
Binding elements works like this that they will be triggered only when they are call.
这篇关于应用中间件后,服务提供商中的访问请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文