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?
BeginnerAnswer
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.