You may not need a dependency injection container if you…
- want to write and maintain SOLID code.
- want to use dependency injection
- don’t want to wire all dependencies manually
- need a central place (“composition root”) for all dependencies
- need a place for your database connection(s)
- want to configure your dependencies in the same way
You may don’t need a container if you…
- want to wire dependencies manually
- load the configuration manually
- only use closures as action handler
- use global variables or custom hacks to handle database connections
A dependencies injection container (DIC) is a tool to define, store and inject the container depedencies. A DIC also acts as a factory for your dependencies. How depedencies are set in the container and how they are configured depend on the DIC implementation.
You (may) need a container when you write SOLID code and use (constructor) dependency injection.
The most common way to inject dependencies is via a class’s constructor. To do this you need to add an argument to the constructor signature to accept the dependency:
final class NewsletterMailer
public function __construct(Mailer $mailer)
$this->mailer = $mailer;
A dependency injection container helps to organize your dependencies.
In a larger codebase it’s getting harder to wire all dependencies manually.
For this reason some container implementations provide a feature called autowiring that detects and injects dependencies automatically for you.