0

Trying to retrieve a deferred service from the IoC in an other service provider fails.

class ServiceProvider extends \Illuminate\Support\ServiceProvider {

    // ...

    public function register() {
        $router = \App::make('router'); // gets resolved
        $hash = \App::make('hash'); // throws an error (Class hash does not exists)
    }

    // ...

}

Changing $deffered = false to true in the HashingServiceProvider resolves this problem. What am I doing wrong?

11
  • 2
    "What am I doing wrong?" Using a static factory to try to do dependency injection. Commented Sep 14, 2014 at 13:46
  • It is not static - are you familiar with laravel's IoC? Commented Sep 14, 2014 at 13:47
  • 1
    Yes::it_is($static) Commented Sep 14, 2014 at 13:56
  • Only because you retrieve it that way, doesn't mean that it is static behind the scenes. All it does is grabbing the shared instance from the IoC that gets provided by the responsible service provider. Commented Sep 14, 2014 at 14:00
  • Shared globally scoped instance. It is static. Globall application state is still global application stat, even if you call it by different name. Stop drinking the damned coolaid. Commented Sep 14, 2014 at 14:07

1 Answer 1

2

If you're relying on another service provider, do it in the boot method:

class ServiceProvider extends \Illuminate\Support\ServiceProvider {

    public function boot ()
    {
        $hash = $this->app['hash'];
    }

}

Here's a quote from the docs:

The register method is called immediately when the service provider is registered, while the boot command is only called right before a request is routed. So, if actions in your service provider rely on another service provider already being registered, or you are overriding services bound by another provider, you should use the boot method.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! I've must have missed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.