在PHP中,依赖注入(Dependency Injection,DI)是一种设计模式,用于降低代码之间的耦合度
MessageService
接口和一个实现该接口的EmailService
类。// MessageService.php
interface MessageService {
public function sendMessage($message);
}
// EmailService.php
class EmailService implements MessageService {
public function sendMessage($message) {
echo "Sending email: {$message}\n";
}
}
Notification
类,它依赖于MessageService
接口。// Notification.php
class Notification {
private $messageService;
public function __construct(MessageService $messageService) {
$this->messageService = $messageService;
}
public function notify($message) {
$this->messageService->sendMessage($message);
}
}
Notification
类,并通过依赖注入提供所需的实现。// index.php
require_once 'EmailService.php';
require_once 'Notification.php';
$emailService = new EmailService();
$notification = new Notification($emailService);
$notification->notify("Hello, this is a notification message!");
在这个例子中,我们通过构造函数将EmailService
实例注入到Notification
类中。这使得Notification
类与具体的实现类解耦,从而提高了代码的可维护性和可测试性。