Access Request in Service Provider After Applying

2019-03-30 16:51发布

问题:

Bindings

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);
}

Now, I want to access foo in my service provider

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

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

回答1:

Try like this:

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.