framework icon indicating copy to clipboard operation
framework copied to clipboard

Defered ServiceProvider is not loaded when accessed through $app['key']

Open ibrasho opened this issue 12 years ago • 4 comments

I'm not sure if this happened to anyone, but trying to use $app['log'] for example in a register() method of a ServiceProvider with throw a ReflectionException.

The reason is that $app['log'] doesn't call Application::loadDeferredProvider('log') like $app->make('log') does, it just delegate the call to Container::offsetGet().

A proposed solution is to make Application extends ArrayAccess, and ensure that Application::offsetGet() load deferred providers if not loaded already.

Of course, one could use App::make in the end, but I prefer to deal with the container in a consistent manner.

Any other ideas? I have a pull request ready if that's the accepted solution.

ibrasho avatar Jul 31 '14 19:07 ibrasho

This can't be the cause. Container::offsetGet calls $this->make, so it must go through Application::make.

JoostK avatar Jul 31 '14 20:07 JoostK

Yes, I've been investigating..

Turns out that $app->deferredProviders doesn't get until all eager providers are registered. Which is why trying to load a deferred provider in the register() method throws an exception.

Any possible solutions?

I'm trying to register a middleware, and I need the Monolog instance.

ibrasho avatar Jul 31 '14 20:07 ibrasho

You shouldn't load any dependencies from the container from register. You can of course do something like the following:

$this->app['key'] = $this->app->share(function($app)
{
    return new Class($app['log']);
});

Now the container lookup is wrapped in a closure so not immediately executed.

JoostK avatar Jul 31 '14 20:07 JoostK

I got around this by passing the class name of the middleware, instead of an instance.

This allows the loading to happen after deferred providers have been registered.

ibrasho avatar Jul 31 '14 21:07 ibrasho