Mateus Guimarães Profile picture
software engineer, teacher and speaker. I mostly talk about programming and powerlifting. Free Lessons here 👉🏻 https://t.co/f7R1qQAEkE

Oct 31, 2022, 8 tweets

Let’s see how the service container works!
The container’s job is to give you objects. When you request an object, it might do that in 2 ways (in Laravel, specifically): either by checking if what you requested is bound already, or by instantiating it.

Okay, cool, but what is a binding?
Imagine the container as a central place that has all the dependencies of your app in an array.
The key is a string: it could be any you want, or it can be a class FQN (which is a string).
The value could be a class FQN, a closure, or null.

So, what are the advantages of using a service container?
First of all, the Laravel framework and packages use it internally — in user land, that means you can swap implementations used by the framework on your app, for example.

It allows us to “Invert control” (it is sometimes called an Inversion of Control Container). What does that mean?
First, let’s see what coupling and dependency injection is.
The code below is coupled to TwilioService and hard to unit test and change.

Dependency injection is injecting the dependencies through arguments, instead of instantiating them. See how that achieves inversion of control.
That has several benefits — you’re not tied to a specific implementation anymore, making changes is easier, testing is easier, etc.

In this situation, we could use the container to give us the class we want.
This is what Laravel does internally to instantiate a controller (that’s why you can type hint a Request class, a service, etc, for example) and many (most) other things.

Laravel’s container offers automatic resolution — that means it will try to instantiate a class even if it is NOT bound. Not all containers do this, and it has limitations (see the previous example type hinting an interface).

If you're interested in learning more, I have a couple videos on it — here's the last one:

And, as always, there's really good documentation around it: laravel.com/docs/9.x/conta…

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling