命令模式將請求封裝為物件,支援參數化、排隊、日誌、撤銷/重做等進階功能。本文完整實作命令模式核心結構,並展開實際應用場景:隊列任務、UI 動作、交易腳本等。
<?php
// 1. 命令介面
interface Command {
public function execute(): void;
public function undo(): void; // 支援撤銷
}
// 2. 接收者:實際業務邏輯
class Light {
private bool $on = false;
private int $brightness = 0;
public function turnOn(): void {
$this->on = true;
echo "燈開啟\n";
}
public function turnOff(): void {
$this->on = false;
echo "燈關閉\n";
}
public function dim(int $level): void {
$this->brightness = $level;
echo "燈光調暗至 $level%\n";
}
public function isOn(): bool { return $this->on; }
}
// 3. 具體命令
class LightOnCommand implements Command {
private Light $light;
private int $prevBrightness = 0;
public function __construct(Light $light) {
$this->light = $light;
}
public function execute(): void {
$this->prevBrightness = $this->light->isOn() ? 100 : 0; // 簡化記錄前狀態
$this->light->turnOn();
}
public function undo(): void {
$this->light->turnOff();
}
}
class LightOffCommand implements Command {
private Light $light;
public function __construct(Light $light) {
$this->light = $light;
}
public function execute(): void {
$this->light->turnOff();
}
public function undo(): void {
$this->light->turnOn();
}
}
class DimLightCommand implements Command {
private Light $light;
private int $level;
private int $prevLevel;
public function __construct(Light $light, int $level) {
$this->light = $light;
$this->level = $level;
}
public function execute(): void {
$this->prevLevel = 100; // 簡化
$this->light->dim($this->level);
}
public function undo(): void {
$this->light->dim($this->prevLevel);
}
}
// 4. 調用者
class RemoteControl {
private ?Command $onCommand = null;
private ?Command $offCommand = null;
private array $history = [];
private int $maxHistory = 50;
public function setCommands(Command $on, Command $off): void {
$this->onCommand = $on;
$this->offCommand = $off;
}
public function pressOn(): void {
if ($this->onCommand) {
$this->onCommand->execute();
$this->record($this->onCommand);
}
}
public function pressOff(): void {
if ($this->offCommand) {
$this->offCommand->execute();
$this->record($this->offCommand);
}
}
public function pressUndo(): void {
$last = array_pop($this->history);
if ($last) {
echo "執行撤銷: ";
$last->undo();
}
}
private function record(Command $cmd): void {
$this->history[] = $cmd;
if (count($this->history) > $this->maxHistory) {
array_shift($this->history);
}
}
}
// 5. 客戶端組裝
$light = new Light();
$remote = new RemoteControl();
$remote->setCommands(new LightOnCommand($light), new LightOffCommand($light));
$remote->pressOn(); // 燈開啟
$remote->pressOff(); // 燈關閉
$remote->pressUndo(); // 執行撤銷: 燈開啟
<?php
interface SerializableCommand extends Command {
public function serialize(): string;
public static function deserialize(string $data): self;
}
class SendEmailCommand implements SerializableCommand {
private string $to;
private string $subject;
private string $body;
private bool $executed = false;
public function __construct(string $to, string $subject, string $body) {
$this->to = $to;
$this->subject = $subject;
$this->body = $body;
}
public function execute(): void {
// 實際發送邏輯
mail($this->to, $this->subject, $this->body);
$this->executed = true;
echo "郵件已寄送至 {$this->to}\n";
}
public function undo(): void {
if ($this->executed) {
echo "無法撤銷已發送郵件,記錄補償動作\n";
// 記錄需人工處理或發送撤銷通知
}
}
public function serialize(): string {
return json_encode([
'class' => self::class,
'to' => $this->to,
'subject' => $this->subject,
'body' => $this->body,
]);
}
public static function deserialize(string $data): self {
$arr = json_decode($data, true);
return new self($arr['to'], $arr['subject'], $arr['body']);
}
}
// 隊列使用
$queue = new SplQueue();
$queue->enqueue(new SendEmailCommand('user@example.com', 'Welcome', 'Hello!'));
$queue->enqueue(new SendEmailCommand('admin@example.com', 'Alert', 'New user'));
// 背景工作者處理
while (!$queue->isEmpty()) {
$cmd = $queue->dequeue();
$cmd->execute();
// 可選:持久化 $cmd->serialize() 至資料庫/Redis 供重試
}
<?php
class MacroCommand implements Command {
private array $commands = [];
public function add(Command $cmd): void {
$this->commands[] = $cmd;
}
public function execute(): void {
foreach ($this->commands as $cmd) {
$cmd->execute();
}
}
public function undo(): void {
// 反向撤銷
foreach (array_reverse($this->commands) as $cmd) {
$cmd->undo();
}
}
}
// 一鍵離家模式
$leaveHome = new MacroCommand();
$leaveHome->add(new LightOffCommand($livingRoomLight));
$leaveHome->add(new LightOffCommand($bedroomLight));
$leaveHome->add(new LockDoorCommand($frontDoor));
$leaveHome->add(new ArmAlarmCommand($alarmSystem));
$remote->setCommands($leaveHome, new DisarmAlarmCommand($alarmSystem));
| 場景 | Command | Receiver | Invoker | 關鍵價值 |
|---|---|---|---|---|
| GUI 按鈕/選單 | 各動作命令 | 業務服務 | 按鈕/選單項 | 解耦 UI 與業務、支援撤銷/重做 |
| 任務隊列 | 可序列化命令 | 服務/模型 | Worker 進程 | 延遲執行、重試、持久化、分散式 |
| 交易腳本 | 資料庫操作命令 | Repository | 腳本執行器 | 原子性、回滾、審計日誌 |
| 巨集錄製 | 巨集命令 | 各子系統 | 錄製器/播放器 | 組合多步驟、參數化播放 |
| API 限流/熔斷 | API 請求命令 | HTTP Client | 限流器 | 統一控制、降級、監控 |
命令模式將「做什麼」與「誰做、何時做」分離,是實現:
PHP 中善用閉包、__invoke、序列化、屬性提升等特性,可大幅減少樣板代碼,專注於業務邏輯。