Interface Type Hints
Type-hinting with interfaces makes functions accept any class that implements the interface — the core of dependency injection and testability.
Type-hinting with interfaces makes functions accept any class that implements the interface — the core of dependency injection and testability.
<?php
interface MailerInterface {
public function send(string $to, string $subject, string $body): bool;
}
class OrderService {
public function __construct(
private MailerInterface $mailer // Accept any implementation
) {}
public function processOrder(array $order): void {
// ... process order ...
$this->mailer->send(
$order["email"],
"Order Confirmed",
"Your order #{$order["id"]} is confirmed."
);
}
}
// Inject any mailer — real or mock
$service = new OrderService(new SmtpMailer());
$service = new OrderService(new SendGridMailer());
$service = new OrderService(new MockMailer()); // for testing
Constructor-inject interfaces rather than concrete classes — code to the abstraction, not the implementation.