应用中间件后Service Provider中的访问请求
Access Request in Service Provider After Applying Middleware
绑定
我在我的服务提供者中使用接口和实现之间的绑定:
public function register()
{
$this->app->bind('MyInterface', MyImplementation::class);
}
中间件
在我的中间件中,我向请求添加了一个属性:
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()。我知道。
如果设置了请求->属性->获取('foo')
,我正在寻找'rebind'的技术
这样试试:
public function register()
{
$this->app->bind('MyInterface', function () {
$request = app(\Illuminate\Http\Request::class);
return app(MyImplementation::class, [$request->foo]);
}
}
绑定元素是这样工作的,它们只有在被调用时才会被触发。
试试这个
public function register()
{
$this->app->bind('MyInterface', function ($app) {
return new MyImplementation(request()->foo);
}
}
在 service provider
您还可以通过以下方式访问 Request Object
:
public function register()
{
$request = $this->app->request;
}
绑定
我在我的服务提供者中使用接口和实现之间的绑定:
public function register()
{
$this->app->bind('MyInterface', MyImplementation::class);
}
中间件
在我的中间件中,我向请求添加了一个属性:
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()。我知道。
如果设置了请求->属性->获取('foo')
,我正在寻找'rebind'的技术这样试试:
public function register()
{
$this->app->bind('MyInterface', function () {
$request = app(\Illuminate\Http\Request::class);
return app(MyImplementation::class, [$request->foo]);
}
}
绑定元素是这样工作的,它们只有在被调用时才会被触发。
试试这个
public function register()
{
$this->app->bind('MyInterface', function ($app) {
return new MyImplementation(request()->foo);
}
}
在 service provider
您还可以通过以下方式访问 Request Object
:
public function register()
{
$request = $this->app->request;
}