Chapter 11. The Container
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, you’ll learn more about what it is, how it works, and how you can use it.
Naming and the Container
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:
-
Application container
-
IoC (inversion of control) container
-
Service 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.
A Quick Introduction to Dependency Injection
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, ...
Get Laravel: Up & Running, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.