Dependency injection separates the code that uses a service from the code that decides which implementation to construct. It is useful when dependencies vary by environment, need test doubles, or represent infrastructure boundaries.
Constructor injection
Pass required collaborators through constructors. This makes dependencies visible and ensures an object cannot be created in an incomplete state. Avoid service locators that allow arbitrary dependencies to be fetched from anywhere.
Define a composition root
The composition root is the application area where concrete implementations are wired together. In a custom PHP application, this may be a bootstrap or container configuration file. Keep this wiring centralized enough to understand, but do not hide all construction behind an elaborate framework.
Use interfaces where they add value
An interface is helpful when multiple implementations are expected or when a stable boundary separates policy from infrastructure. Creating an interface for every class adds maintenance without necessarily improving flexibility.
Scope object lifetimes
Distinguish request-scoped services, stateless shared services, and resources that must be closed. Avoid sharing mutable request-specific state across requests in long-running workers.
Checklist
- Prefer constructor injection for required dependencies.
- Centralize concrete wiring.
- Introduce interfaces at real boundaries.
- Avoid global service-locator access.
- Define object lifetime and mutable-state rules.