阅读量:126
在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类与具体的实现类解耦,从而提高了代码的可维护性和可测试性。