Dependency Injection — a practical guide to dependency injection PHP with clear examples you can reuse in real projects.
OOP Tutorial Series (37/65). Prefer one article? Read the complete OOP tutorial.
Short description
Dependency Injection (DI) improves testing and flexibility. Inject interfaces, not concrete classes, when useful.
Constructor injection
interface Mailer { public function send(string $to, string $body): void; }
class WelcomeService {
public function __construct(private Mailer $mailer) {}
public function welcome(string $email): void {
$this->mailer->send($email, 'Welcome!');
}
}