萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 設計模式:命令模式完整實作與應用場景

命令模式將請求封裝為物件,支援參數化、排隊、日誌、撤銷/重做等進階功能。本文完整實作命令模式核心結構,並展開實際應用場景:隊列任務、UI 動作、交易腳本等。

核心角色與 UML 關係

  • Command(命令介面):宣告 `execute()` 方法
  • ConcreteCommand(具體命令):綁定 Receiver 與具體行為,實作 `execute()`
  • Receiver(接收者):執行實際業務邏輯的物件
  • Invoker(調用者/請求者):持有命令物件,觸發 `execute()`
  • Client(客戶端):建立命令、設定接收者、配置調用者

基礎實作

<?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));

實戰場景對照表

場景CommandReceiverInvoker關鍵價值
GUI 按鈕/選單各動作命令業務服務按鈕/選單項解耦 UI 與業務、支援撤銷/重做
任務隊列可序列化命令服務/模型Worker 進程延遲執行、重試、持久化、分散式
交易腳本資料庫操作命令Repository腳本執行器原子性、回滾、審計日誌
巨集錄製巨集命令各子系統錄製器/播放器組合多步驟、參數化播放
API 限流/熔斷API 請求命令HTTP Client限流器統一控制、降級、監控

PHP 特有實作細節

  • 閉包即命令:`$cmd = fn() => $service->doSomething(); $cmd();` 簡單場景無需正式類別
  • __invoke 魔術方法:類別實作 `__invoke` 即可當作 callable 直接呼叫
  • 屬性提升 (PHP 8.0+):`public function __construct(private Light $light) {}` 簡化屬性宣告
  • 唯讀屬性 (PHP 8.1+):命令參數不可變,`public readonly string $to;`
  • 序列化介面:實作 `Serializable` 或 `__serialize/__unserialize` (PHP 7.4+)

總結

命令模式將「做什麼」與「誰做、何時做」分離,是實現:

  1. 解耦:調用者不需知道接收者細節
  2. 擴充:新增命令不修改現有代碼(開放封閉原則)
  3. 進階控制:撤銷、重做、隊列、日誌、交易、巨集

PHP 中善用閉包、__invoke、序列化、屬性提升等特性,可大幅減少樣板代碼,專注於業務邏輯。

copyright © 萬盛學電腦網 all rights reserved