Access Request in Service Provider After Applying Middleware

让人想犯罪 __ 提交于 2019-12-05 01:47:11

问题


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.




回答2:


In service provider You can also access Request Object by:

public function register()
{
    $request = $this->app->request;
}



回答3:


Try this

public function register()
{
    $this->app->bind('MyInterface', function ($app) {
        return new MyImplementation(request()->foo);
    }
}


来源:https://stackoverflow.com/questions/37555236/access-request-in-service-provider-after-applying-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!