Laravel Introduction to Service Providers

Service providers are the backbone of the framework and the central place of bootstrapping. Everything is bootstrapped by the service providers.

Bootstrapping, bootstrapping, bootstrapping… what is this?

Generally bootstrapping means registering things, including container bindings, event listeners, middleware (we will talk about them soon enough👀), etc.

In our config/app.php we can see a list of core providers that will be loaded for the application. This includes Laravel components such as mailers, queue, cache, auth, routing, etc.

What better way to learn than to do it yourself!

Firstly we have to know that all service providers extend Illuminate\Support\ServiceProvider and they mostly contain a register() and boot() method.

Just like… this

Warning: You should never attempt to register an event listener, routes or any other functionality within the register method

Tip: You can make your own Service Provider by running the following command: php artisan make:provider YourNameProvider (please append Provider to your provider classes, it makes it much easier to read for other people and you!)

Here we should only bind into the service container, and never attempt to register any other functionality!

If you do that you have the risk to use a service that is provided by a service provider that has not loaded yet!

To access the container we always do it through our $app parameter ( which you should remember from the Laravel Lifecycle article, and if you don’t, go read it)

And the way we register a provider is like… this

What is going on in here? We have 2 bindings of different classes ( that for argument’s sake let’s say implement the same contract/interface ).

When we will use our provider it will give us an implementation of either class depending on what have called the provider with. This way we can implement, let’s say, 2 HTTP clients in a single HTTP Provider and use it everywhere in our program ( instead of implementing something more complex like factory design patterns ).

This method will only run after all other service providers are registered. You know what that means right? You have access to ALL the other services that have been registered!

Also, you can type-hint any dependencies in the boot method and the container will handle the dependency injection for you!

Web Developer