Design Patterns

Dependency Injection and IoC Containers

Invert control of dependency creation to keep classes decoupled from their collaborators and trivially testable.

March 6, 2026
#dependency-injection#design-patterns#clean-architecture

Dependency Injection means that a class receives its collaborators from the outside rather than creating them itself. Constructor injection is the clearest form: the dependencies are declared as constructor parameters and provided at instantiation. This inverts control — the class no longer owns its dependencies' lifecycle — and makes substitution (for testing or configuration) straightforward without any mocking framework.

php
class OrderService
{
    public function __construct(
        private readonly OrderRepository $orders,
        private readonly EventBus $events,
        private readonly Clock $clock,
    ) {}
}

// In a test — plain PHP, no container:
$service = new OrderService(
    new InMemoryOrderRepository(),
    new RecordingEventBus(),
    new FixedClock('2026-03-06'),
);
Constructor injection — no container magic needed in tests

Continue reading

Dependency Injection and IoC Containers | Architecture Hub