Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

makapaka's avatar

Custom service provider boot method not running

I have an observer and the docs state You may register observers in the boot method of one of your service providers.

So in my custom provider

class DraftServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function boot() {
         Options::observe(OptionsObserver::class);

}

The provider is registered in the app.php, and I know it works as it loads some other singletons that are working as I expect.

However, the observer above does not work.

If i put this observer registration in the AppServiceProvider::boot method, it does work as expected.

I would like to keep it in my custom provider though, as its a DeferrableProvider - could this be the issue ? Does that not execute a boot method ?

Thanks

0 likes
6 replies
makapaka's avatar

bah, never mind, i guess its because that being deferred, none of the provided classes are loading so the boot isnt loading ?

martinbean's avatar

@makapaka Yeah, that’s right. The service provider’s method won’t be invoked until you ask for something you say it provides. For example:

class FooServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register()
    {
        $this->app->singleton(Foo::class, function () {
            return new Foo();
        });
    }

    public function provides()
    {
        return [
            Foo::class,
        ];
    }
}

In the above, the service provider registers a class called Foo, but only when you actually try and resolve it. If you don’t during a request, then the service provider’s methods won’t be called during that request.

This is handy for binding things to the container only as and when you need. So things like payment gateways or whatever that may not be needed on every request.

1 like
O_Josh_AJ's avatar

@martinbean, are you saying for every request, the register and boot methods of every service provider is called?

I've found this confusing, whether it's upon every request or only once at the bootstrapping stage.

Thanks.

martinbean's avatar

are you saying for every request, the register and boot methods of every service provider is called?

@Programmer_Josh Yes. The register method of all service providers are called first, to allow service providers to register services in the service container. Then the boot method of each service provider is called.

The boot method is where you put logic knowing all services have been registered, so where you should put things like extensions.

1 like

Please or to participate in this conversation.