Back to results for “Dependency injection”
PHP › Dependency Injection & Service Containers

What is dependency injection, and how does it improve the design of PHP applications compared to creating dependencies directly inside a class?

Beginner

Answer

Dependency injection is a design pattern where a class receives the objects it depends on from an outside source, typically through its constructor, rather than creating those dependencies itself internally, which makes the class more flexible, easier to test since dependencies can be replaced with test doubles, and more loosely coupled since the class does not need to know exactly how its dependencies are constructed.
class OrderService {
    private $mailer;
    public function __construct(Mailer $mailer) {
        $this->mailer = $mailer;
    }
}
$service = new OrderService(new Mailer());
Real-world example An order processing class receives a Mailer object through its constructor rather than creating one internally, allowing tests to easily substitute a fake mailer that simply records what would have been sent, without actually sending real emails during testing.

Common follow-ups: What is the difference between constructor injection and setter injection?;Why does dependency injection make unit testing significantly easier?