Laravel 5: Service Provider

Service Provider


Service providers are the central place of all Laravel application bootstrapping.
Your own application, as well as all of Laravel’s core services are bootstrapped via service providers.

OK, let’s talk plain English.

Laravel needs to know, what it has at its disposal and all that info is being channeled (bootstrapped) to it via Service Provider.

Here what we can place in Service Provider:
  • service container bindings,
  • event listeners,
  • middleware,
  • routes
How binding is done was explained (as far as simple binding is concerned) here.
Service provider can be generated using Artisan CLI, like this:

Generated provider file will be placed in directory:

Newly generated Service Provider must be registered.
You can do this in:

Just add it to array of providers – look for this and follow way other providers were registered:

Deferred providers.

Sometimes you may want to have providers loaded lazy (when needed only).

For that use deferred providers.

You do it same way as other providers, with two differences:

you are setting protected property and set its value to true:

then you are creating property provides() and pacing reference to deferred provider right there:

That is all.
MyProviderKeyword provider will load on-demand only.

This approach may speed up your app.

 


More about providers in Laravel docs.