Laravel service providers explained in 2 mins

Marvioso
2 min readDec 23, 2020

--

Start talking to a new Laravel developer about service providers and you may find a confused glaze spread slowly over their face. Chances are they’ve read about them briefly in the docs, but for many this is not an area they are fully comfortable with.

In part, a lot of this comes from how interlinked this feature is with the concept of dependency injection, something that can appear very daunting for new developers.

In actual fact — whilst service providers are commonly used to manage dependency injection — at their heart they are pretty straight forward.

Imagine building a brand-new app. Invariably every app needs a central place where a developer can do “stuff” that they know will affect their entire application.

Service providers are this place.

Contrast with a controller for example, which handles only individual specific requests. Or middleware, which transforms groups of requests before they hit the controller. Both these are great patterns to manage the flow of our incoming requests, but what if we want to run code before this happens — right at the start of the process when our app first boots up?

If you come from a Wordpress background you may be familiar with the functions.php file. This is effectively the same concept as a Laravel service provider — a place to run code that will affect your entire app before any of your other custom code.

There is one helpful difference though — Laravel allows us to have multiple service providers.

This enables us to separate our responsibilities and organise our code more elegantly then having a single file to dump code into. It also allows package developers to manage the needs of their package separately to the other needs of the app.

Each of your service providers is defined wherever your app is bootstrapped (eg. bootstrap/providers.php) and are “fired-up” by Laravel when it first runs.

And it’s really as simple as that!

One last thing…you may be asking how then does this tie back with the aforementioned concept of dependency injection. Well…in a nutshell, developers need a central place when they can define the bindings for each of their dependencies before any of their other code runs— and Laravel service providers offer the perfect place to setup these bindings.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Marvioso
Marvioso

Written by Marvioso

Marvioso is a full-stack software developer living and working in the UK

Responses (1)

Write a response