觀察者模式定義對象間一對多依賴,當主題狀態改變時自動通知所有觀察者。PHP SPL (Standard PHP Library) 內建 SplSubject、SplObserver 標準接口,無需手寫介面即可實現標準觀察者模式。
interface SplSubject {
public function attach(SplObserver $observer);
public function detach(SplObserver $observer);
public function notify();
}
interface SplObserver {
public function update(SplSubject $subject);
}
<?php
/** 主題:股票價格 */
class StockPrice implements SplSubject {
private $observers = [];
private $symbol;
private $price;
public function __construct(string $symbol, float $initialPrice) {
$this->symbol = $symbol;
$this->price = $initialPrice;
}
public function attach(SplObserver $observer) {
$this->observers[] = $observer;
}
public function detach(SplObserver $observer) {
$key = array_search($observer, $this->observers, true);
if ($key !== false) unset($this->observers[$key]);
}
public function notify() {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setPrice(float $price) {
$this->price = $price;
$this->notify(); // 價格變動觸發通知
}
public function getPrice(): float { return $this->price; }
public function getSymbol(): string { return $this->symbol; }
}
/** 觀察者:投資者 */
class Investor implements SplObserver {
private $name;
private $threshold;
public function __construct(string $name, float $threshold) {
$this->name = $name;
$this->threshold = $threshold;
}
public function update(SplSubject $subject) {
if (!$subject instanceof StockPrice) return;
$price = $subject->getPrice();
$symbol = $subject->getSymbol();
if ($price >= $this->threshold) {
echo "[{$this->name}] 警報!{$symbol} 價格達到 {$price} (閾值: {$this->threshold})<br/>";
} else {
echo "[{$this->name}] {$symbol} 當前價格: {$price}<br/>";
}
}
}
/** 觀察者:日誌記錄器 */
class PriceLogger implements SplObserver {
public function update(SplSubject $subject) {
if (!$subject instanceof StockPrice) return;
$log = sprintf('[%s] %s: %.2f', date('H:i:s'), $subject->getSymbol(), $subject->getPrice());
error_log($log . PHP_EOL, 3, __DIR__ . '/price.log');
}
}
// 使用示範
$stock = new StockPrice('TSMC', 500.0);
$investor1 = new Investor('張三', 550);
$investor2 = new Investor('李四', 600);
$logger = new PriceLogger();
$stock->attach($investor1);
$stock->attach($investor2);
$stock->attach($logger);
echo "--- 價格變動測試 ---<br/>";
$stock->setPrice(520); // 未觸發閾值
$stock->setPrice(560); // 觸發張三警報
$stock->setPrice(610); // 觸發張三、李四警報
$stock->detach($investor1);
echo "--- 張三取消訂閱後 ---<br/>";
$stock->setPrice(620); // 僅李四收到
?>
--- 價格變動測試 ---
[張三] TSMC 當前價格: 520
[李四] TSMC 當前價格: 520
[張三] 警報!TSMC 價格達到 560 (閾值: 550)
[李四] TSMC 當前價格: 560
[張三] 警報!TSMC 價格達到 610 (閾值: 550)
[李四] 警報!TSMC 價格達到 610 (閾值: 600)
--- 張三取消訂閱後 ---
[李四] 警報!TSMC 價格達到 620 (閾值: 600)
| 場景 | 主題 | 觀察者 |
|---|---|---|
| 事件驅動架構 | EventDispatcher | Listener/Subscriber |
| 快取失效 | Entity 更新 | CacheWarmer, CDN Purge |
| 日誌/審計 | Model 生命週期 | AuditLogger, ActivityFeed |
| 即時通知 | Order 狀態變更 | EmailNotifier, SmsGateway, WebSocketPusher |
| UI 綁定 | ViewModel | Vue/React 組件 (透過 JS 實現) |