要解耦 PHP 消息通知,可以考慮使用事件驅(qū)動(dòng)的設(shè)計(jì)模式。以下是一種可能的解耦方案:
interface EventInterface {
public function getData();
}
class EmailNotifier {
public function sendEmail(EventInterface $event) {
// 發(fā)送郵件通知
}
}
class SMSNotifier {
public function sendSMS(EventInterface $event) {
// 發(fā)送短信通知
}
}
// 創(chuàng)建其他監(jiān)聽器...
class EventDispatcher {
private $listeners = [];
public function addListener($eventName, $listener) {
$this->listeners[$eventName][] = $listener;
}
public function dispatch($eventName, EventInterface $event) {
if (isset($this->listeners[$eventName])) {
foreach ($this->listeners[$eventName] as $listener) {
$listener->$eventName($event);
}
}
}
}
$dispatcher = new EventDispatcher();
$dispatcher->addListener('event1', new EmailNotifier());
$dispatcher->addListener('event1', new SMSNotifier());
// 注冊(cè)其他監(jiān)聽器...
class EventGenerator {
private $dispatcher;
public function __construct(EventDispatcher $dispatcher) {
$this->dispatcher = $dispatcher;
}
public function doSomething() {
// 執(zhí)行操作...
// 觸發(fā)事件
$event = new Event1($data);
$this->dispatcher->dispatch('event1', $event);
}
}
// 創(chuàng)建其他事件...
$dispatcher = new EventDispatcher();
$eventGenerator = new EventGenerator($dispatcher);
$eventGenerator->doSomething();
以上代碼示例中,通過使用事件驅(qū)動(dòng)的設(shè)計(jì)模式,我們將業(yè)務(wù)邏輯和消息通知解耦。當(dāng)需要添加新的消息通知方式時(shí),只需創(chuàng)建一個(gè)新的監(jiān)聽器,并在適當(dāng)?shù)牡胤阶?cè)即可,而不需要修改原有的業(yè)務(wù)邏輯。