Laravel’s service container, or dependency injection container, sits at the core of almost every other feature. The container is a simple tool you can use to bind and resolve concrete instances of classes and interfaces, and at the same time it’s a powerful and nuanced manager of a network of interrelated dependencies. In this chapter, we’ll learn more about what it is, how it works, and how you can use it.
You’ll notice in this book, in the documentation, and in other educational sources that there are quite a few names folks use for the container. These include:
IoC (inversion of control) container
DI (dependency injection) container
All are useful and valid, but just know they’re all talking about the same thing. They’re all referring to the service container.
Dependency injection means that, rather than being instantiated (“newed up”) within a class, each class’s dependencies will be injected in from the outside. This most commonly occurs with constructor injection, which means an object’s dependencies are injected when it’s created. But there’s also setter injection, where the class exposes a method specifically for injecting a given dependency, and method injection, where one or more methods expect their dependencies to be injected when they’re called.
Take a look at Example 11-1 for a quick example of constructor injection, ...