应用中间件后服务提供商中的访问请求

sch*_*rht 5 ioc-container laravel laravel-5

绑定

我在接口和实现之间的服务提供程序中使用绑定:

public function register()
{
    $this->app->bind('MyInterface', MyImplementation::class);
}
Run Code Online (Sandbox Code Playgroud)

中间件

在我的中间件中,我向请求添加了一个属性:

public function handle($request, Closure $next)
{
    $request->attributes->add(['foo' => 'bar]);
    return $next($request);
}
Run Code Online (Sandbox Code Playgroud)

现在,我想访问foo我的服务提供商

public function register()
{
    $this->app->bind('MyInterface', new MyImplementation($this->request->attributes->get('foo')); // Request is not available
}
Run Code Online (Sandbox Code Playgroud)

在应用中间件之前调用register().我知道.

如果设置了request-> attributes-> get('foo'),我正在寻找一种"重新绑定"的技术

Fil*_*ski 17

试试这样:

public function register()
{
    $this->app->bind('MyInterface', function () {
        $request = app(\Illuminate\Http\Request::class);

        return app(MyImplementation::class, [$request->foo]);
    }
}
Run Code Online (Sandbox Code Playgroud)

绑定元素的工作原理是只有在调用它们时才会触发它们.

  • 绝对不.这就是IoC容器的工作原理,这也是它的优势之一. (3认同)

Ada*_*ski 7

service provider您还可以Request Object通过以下方式访问:

public function register()
{
    $request = $this->app->request;
}
Run Code Online (Sandbox Code Playgroud)