Inversion of Control and Dependency Injection
Laravel Saga · Season 0 · Episode 07
In the previous episode, we ended with a question hanging in the air: if the CheckoutService receives its dependencies through its constructor, who creates those dependencies and hands them over?
Today we'll answer it. First, I want to separate four concepts that are constantly confused: Dependency Inversion, Inversion of Control, Dependency Injection and Service Locator. Then we'll roll up our sleeves and build a working dependency injection container, with autowiring, in about 90 lines of PHP.
This is perhaps the most important episode of the season for anyone who wants to understand Laravel from the inside. So grab a coffee and come along.
Four concepts, four different things
| Concept | What it is | Kind |
|---|---|---|
| Dependency Inversion Principle (DIP) | Depend on abstractions, not on implementations | Design principle |
| Inversion of Control (IoC) | The framework, not your code, controls the flow and the creation of objects | Architectural principle |
| Dependency Injection (DI) | Handing an object its dependencies ready-made, instead of it creating them | Technique |
| DI Container | A tool that automates creation and injection | Tool |
If I had to sum it up in one sentence: the DIP says what to depend on; DI says how to receive those dependencies; the container automates DI; and IoC is the broader idea that embraces all of it.
- middleware
- events
- jobs
- commands
- constructor
- setter
- method parameter
- bind
- singleton
- make
- abstractions
- contracts
Inversion of Control: "don't call us, we'll call you"
In a "traditional" program, your code is in control of everything. It calls the libraries, creates the objects and decides the order of things:
php// Your code in control
$db = new PDO('mysql:host=localhost;dbname=app', 'root', 'secret');
$repo = new UserRepository($db);
$user = $repo->find($_GET['id']);
echo json_encode($user);With a framework, that control is inverted. The framework runs the main flow and calls your code at the right moments:
php// The framework is in control; you just fill in the gaps
class UserController
{
public function show(User $user)
{
return $user;
}
}Think about it: you never call UserController::show(). Laravel does. It receives the request, works out the route, creates the controller, fetches the user from the database, calls the method and turns the return value into JSON. You only wrote the part that matters.
That's Inversion of Control, and it's what defines the difference between a library (you call it) and a framework (it calls you). Middleware, events, service providers, Artisan commands, jobs: they're all examples of IoC. You write the pieces, and the framework decides when to run them.
Dependency Injection: the three ways
Injecting a dependency is just a fancy name for "handing the ready-made dependency to the object that needs it". And there are three ways to do it.
Through the constructor, which is the most common and the one I recommend in most cases:
phpclass InvoiceService
{
public function __construct(private PdfRenderer $pdf) {}
}The dependency is mandatory, and the object is born complete.
Through a setter method:
phpclass InvoiceService
{
private ?Logger $logger = null;
public function setLogger(Logger $logger): void
{
$this->logger = $logger;
}
}It works for optional dependencies, but the object can exist in an incomplete state, and that tends to cause headaches.
Through a method parameter:
phpclass InvoiceController
{
public function download(Invoice $invoice, PdfRenderer $pdf)
{
return $pdf->render($invoice);
}
}Here the dependency is only needed in that method. Laravel supports this form in controllers, in the handle method of jobs and in Artisan commands.
The problem: assembling the object tree
With DI, each class declares what it needs. Great. But somewhere, the whole tree of objects has to be assembled. And it can end up like this:
php$checkout = new CheckoutService(
new StripeGateway(
new HttpClient(timeout: 10),
getenv('STRIPE_SECRET'),
),
new OrderRepository(
new DatabaseConnection(getenv('DB_DSN')),
),
new Mailer(
new SmtpTransport(getenv('MAIL_HOST')),
),
new Logger('checkout'),
);The place where everything is assembled has a name: the composition root. In a small application, assembling everything by hand works. Now imagine this with hundreds of classes. It's unworkable. And this is where the container comes in.
Building a container from scratch
Time to do it. Our container will have three abilities:
bind: teach it how to create something (a concrete class for an interface, or a closure).singleton: the same asbind, but always reusing the same instance.make: create an object, resolving its dependencies on its own through Reflection. That's the famous autowiring.
php<?php
declare(strict_types=1);
final class Container
{
private array $bindings = [];
private array $instances = [];
public function bind(string $abstract, Closure|string|null $concrete = null, bool $shared = false): void
{
$this->bindings[$abstract] = [
'concrete' => $concrete ?? $abstract,
'shared' => $shared,
];
}
public function singleton(string $abstract, Closure|string|null $concrete = null): void
{
$this->bind($abstract, $concrete, shared: true);
}
public function make(string $abstract): object
{
// 1. Is there already a shared instance?
if (isset($this->instances[$abstract])) {
return $this->instances[$abstract];
}
// 2. Is there a binding? If not, try the class itself
$binding = $this->bindings[$abstract] ?? ['concrete' => $abstract, 'shared' => false];
$concrete = $binding['concrete'];
// 3. A closure? Run it. Another class? Resolve it. Otherwise, build it through Reflection
$object = match (true) {
$concrete instanceof Closure => $concrete($this),
$concrete !== $abstract => $this->make($concrete),
default => $this->build($concrete),
};
// 4. Is it a singleton? Keep it for next time
if ($binding['shared']) {
$this->instances[$abstract] = $object;
}
return $object;
}
private function build(string $class): object
{
$reflection = new ReflectionClass($class);
if (! $reflection->isInstantiable()) {
throw new RuntimeException("[{$class}] cannot be instantiated. Missing a binding?");
}
$constructor = $reflection->getConstructor();
if ($constructor === null) {
return new $class();
}
$dependencies = array_map(
fn (ReflectionParameter $parameter) => $this->resolveParameter($parameter, $class),
$constructor->getParameters(),
);
return $reflection->newInstanceArgs($dependencies);
}
private function resolveParameter(ReflectionParameter $parameter, string $class): mixed
{
$type = $parameter->getType();
// Parameter typed with a class or interface: resolve it recursively
if ($type instanceof ReflectionNamedType && ! $type->isBuiltin()) {
return $this->make($type->getName());
}
// Does it have a default value? Use it
if ($parameter->isDefaultValueAvailable()) {
return $parameter->getDefaultValue();
}
throw new RuntimeException("Don't know how to resolve parameter \${$parameter->getName()} of [{$class}].");
}
}Notice that the heart of the container lives in the build() and resolveParameter() methods. And they use exactly the Reflection technique we saw in episode 04: read the constructor, find out the type of each parameter and call make() again, recursively, for each dependency.
Singleton
Second call to a singleton
The instance is already in instances[]. The container returns the same object without building anything.
Closure
Binding with a closure
For the PaymentGateway interface, the binding says how to create it: the closure runs and returns a StripeGateway with the right key.
Autowiring
Concrete class without a binding
The CheckoutService was never configured. build() reads the constructor and calls make() again for each typed parameter.
No binding
Interface without a binding
Autowiring reaches an interface and doesn't know which class to use. That's the "cannot be instantiated. Missing a binding?".
BindingResolutionException in Laravel
Taking it for a spin
Let's test it with a few classes:
phpinterface PaymentGateway
{
public function charge(int $amount): string;
}
final class StripeGateway implements PaymentGateway
{
public function __construct(private string $secret) {}
public function charge(int $amount): string
{
return "Stripe charged {$amount}";
}
}
final class Logger
{
public array $lines = [];
public function info(string $message): void
{
$this->lines[] = $message;
}
}
final class CheckoutService
{
public function __construct(
private PaymentGateway $gateway,
private Logger $logger,
) {}
public function finish(int $amount): string
{
$result = $this->gateway->charge($amount);
$this->logger->info($result);
return $result;
}
}
$container = new Container();
// We only teach what autowiring can't guess
$container->singleton(Logger::class);
$container->bind(PaymentGateway::class, fn () => new StripeGateway('sk_test_123'));
// We never configured the CheckoutService: autowiring resolves it on its own
$checkout = $container->make(CheckoutService::class);
echo $checkout->finish(5000); // Stripe charged 5000
var_dump($container->make(Logger::class) === $container->make(Logger::class));
// true: singleton, always the same instance
var_dump($container->make(CheckoutService::class) === $checkout);
// false: no binding, every make() creates a new objectThis code has been tested and works exactly as it is here. I strongly suggest you run it on your machine too.
Now, look at what happens if we forget the interface binding:
php(new Container())->make(CheckoutService::class);
// RuntimeException: [PaymentGateway] cannot be instantiated. Missing a binding?If you already work with Laravel, you've probably seen the "official" version of this error: BindingResolutionException: Target [App\Contracts\PaymentGateway] is not instantiable. And now you know exactly why it happens. Autowiring found an interface along the way, and nobody said which class to use.
Why some things need a binding
Autowiring manages on its own when all the parameters are concrete classes. It needs your help in two cases:
- Interfaces and abstract classes: which implementation should it use?
- Primitive values: what is the value of
string $secret?
That's what bindings are for. And where do bindings live in a Laravel application? In Service Providers, which you'll get to know in detail in the saga.
Swapping implementations in tests
And now the moment when all of this pays off. Look how easy testing becomes:
phpfinal class FakeGateway implements PaymentGateway
{
public array $charges = [];
public function charge(int $amount): string
{
$this->charges[] = $amount;
return 'fake';
}
}
$container->singleton(PaymentGateway::class, FakeGateway::class);
$container->make(CheckoutService::class)->finish(5000);
assert($container->make(PaymentGateway::class)->charges === [5000]);Not a single line of the CheckoutService changed. No card was actually charged. In Laravel, that's exactly what $this->app->instance(...), $this->mock(...) and fakes like Mail::fake() and Queue::fake() do.
What Laravel's container has on top
Our container fits in about 90 lines; Laravel's has thousands. To give you an idea of what's ahead in the saga, these are the main differences:
| Feature | What it's for |
|---|---|
scoped() | An instance shared per request or job, reset every cycle (essential with Octane) |
instance() | Registering an object that's already built |
| Contextual binding | Different implementations of the same interface for different classes |
| Contextual attributes | #[Config('app.name')], #[CurrentUser] right on the parameter |
| Method injection | $container->call([$obj, 'method']) resolves the method's parameters |
| Tags | Grouping bindings and resolving all of them at once |
| Extenders and callbacks | Decorating or reacting to objects when they're resolved |
| Circular dependency detection | A clear error when A needs B, which needs A |
Service Locator: the controversial cousin
Before wrapping up, I need to introduce a pattern that looks like Dependency Injection but isn't: the Service Locator. With it, instead of receiving its dependencies, the class asks the container for them.
php// Dependency Injection: receives
class ReportService
{
public function __construct(private Cache $cache) {}
}
// Service Locator: asks
class ReportService
{
public function generate(): array
{
$cache = app('cache'); // or Cache::get(...)
}
}The problem with the Service Locator is that it hides dependencies. Looking only at the constructor, you can't tell what the class needs. That's why many people consider it an anti-pattern.
And here comes a revelation that may sting a little: in Laravel, the app() helper and Facades work as a form of Service Locator. The framework accepts this trade-off consciously. Facades are practical, readable and, because they always consult the container, they remain testable, since you can swap the object behind them.
A rule that works well in practice: in domain classes, services and actions, prefer constructor injection. In routes, views and "glue" code, facades and helpers are perfectly acceptable.
What to take into the saga
- IoC: the framework controls the flow and calls your code.
- DI: objects receive their dependencies ready-made, instead of creating them.
- A container automates DI with bindings and autowiring through Reflection.
- Interfaces and primitive values need a binding; concrete classes don't.
- Facades and
app()are a form of Service Locator: practical, but they hide dependencies.
Next episode
We've just built a container, and it's already a design pattern in action. But Laravel uses many others: Front Controller, Facade, Strategy, Adapter, Pipeline, Observer, Active Record, Builder...
In the next episode, we'll take a tour of the classic design patterns inside Laravel. And instead of abstract examples, I'll show you the exact place where each one appears in the framework. See you in episode 08.
References and further reading
Essential reading
- Inversion of Control Containers and the Dependency Injection pattern, by Martin Fowler: the article that popularised the term "Dependency Injection".
- Inversion of Control, by Martin Fowler: the difference between a library and a framework.
- Service Locator is an Anti-Pattern, by Mark Seemann: the classic argument against the Service Locator.
Official documentation
- Laravel's Service Container: the professional version of the container built in this article.
- Laravel Facades, including the "Facades vs. Dependency Injection" section.
- PSR-11: Container Interface.
Book
- Dependency Injection Principles, Practices, and Patterns, by Mark Seemann and Steven van Deursen (Manning). The most complete reference on the subject.