dependency-injection
Dependency Injection Best Practices for PHP
When to Use a DI Container (and When NOT to)
A DI container is an infrastructure concern. Use it for applications that need flexible wiring, interface swapping, or framework integration. Libraries should use constructor injection directly and let the consumer resolve dependencies.
| Use a DI Container For | Do Not Use a Container For |
|---|---|
| Applications with many interchangeable services | Libraries and packages |
| Need to swap implementations (test vs production) | Simple scripts with one or two classes |
| Framework integration (Symfony, Laravel) | Throwaway code or prototypes |
The container should wire the application together at the edge, while the core remains ignorant of the container. This skill provides the rules for registering dependencies, migrating legacy locators, and injecting objects.
A Plugin is the purpose this wiring serves: define extension points (Ports) so new behavior is added by plugging in implementations (Adapters) at the composition root, without modifying the core. A plugin must extend the existing abstractions, never bypass them. It protects the framework / extension boundary — one of a family of boundary-protection patterns (with Gateway, Mapper, Remote Facade, DTO, and Special Case) that form the foundation of Hexagonal architecture; see boundary-protection-patterns.md.