Overview
Dependency injection means an object receives the collaborators it needs rather than creating them internally. In a custom PHP application, this can reduce hidden coupling without requiring a large framework or a complex container.
Constructor injection
A service should declare the dependencies required for its work:
final class ReportService
{
public function __construct(
private ReportRepository $reports,
private MailerInterface $mailer
) {}
public function send(int $reportId): void
{
$report = $this->reports->find($reportId);
if ($report === null) {
throw new RuntimeException('Report not found.');
}
$this->mailer->sendReport($report);
}
}
The service does not need to know how the repository connects to MySQL or which mail provider is used. Those details are assembled at the application boundary.
Compose dependencies in one place
A small application can use a bootstrap or composition root:
$pdo = Database::connection();
$reports = new PdoReportRepository($pdo);
$mailer = new SmtpMailer($mailConfig);
$reportService = new ReportService($reports, $mailer);
Avoid scattering new PDO, mail client construction or global configuration reads throughout business services. Central composition makes dependencies visible.
Do not over-abstract
An interface is useful when there are meaningful alternative implementations or a test seam. Creating interfaces for every class can add noise. Start with dependencies that cross infrastructure boundaries, such as repositories, clocks, mailers and external API clients.
Testing benefits
A unit test can inject a fake mailer and an in-memory repository. This makes the test deterministic and avoids sending real email or requiring a live database. Test the service's behavior, not the internal wiring.
Checklist
- Prefer constructor injection for required dependencies.
- Build the object graph in one composition root.
- Keep infrastructure creation out of domain services.
- Introduce interfaces where they create real flexibility.
- Use fakes for external effects in tests.
- Avoid a service locator that hides dependencies.
References
PHP-FIG PSR-11 Container Interface · PHP Manual: Classes and Objects