命令模式將「請求」封裝為物件,從而使您可用不同的請求對客戶進行參數化、對請求排隊或記錄請求日誌、支援可撤銷操作。本文提供完整 PHP 實作與實用場景。
execute() 方法execute()execute()<?php
/**
* 命令介面
*/
interface Command {
public function execute();
}
/**
* 具體命令:開燈
*/
class LightOnCommand implements Command {
private $light;
public function __construct(Light $light) {
$this->light = $light;
}
public function execute() {
$this->light->turnOn();
}
}
/**
* 具體命令:關燈
*/
class LightOffCommand implements Command {
private $light;
public function __construct(Light $light) {
$this->light = $light;
}
public function execute() {
$this->light->turnOff();
}
}
/**
* 接收者:燈
*/
class Light {
private $location;
public function __construct($location) {
$this->location = $location;
}
public function turnOn() {
echo "{$this->location} 燈已開啟\n";
}
public function turnOff() {
echo "{$this->location} 燈已關閉\n";
}
}
/**
* 請求者:遙控器
*/
class RemoteControl {
private $commands = [];
public function setCommand($slot, Command $command) {
$this->commands[$slot] = $command;
}
public function pressButton($slot) {
if (isset($this->commands[$slot])) {
$this->commands[$slot]->execute();
}
}
}
/**
* 客戶端測試
*/
$light = new Light('客廳');
$lightOn = new LightOnCommand($light);
$lightOff = new LightOffCommand($light);
$remote = new RemoteControl();
$remote->setCommand('on', $lightOn);
$remote->setCommand('off', $lightOff);
$remote->pressButton('on'); // 輸出:客廳 燈已開啟
$remote->pressButton('off'); // 輸出:客廳 燈已關閉
interface UndoableCommand extends Command {
public function undo();
}
class DimmerLightCommand implements UndoableCommand {
private $light;
private $prevLevel;
public function __construct(Light $light) {
$this->light = $light;
}
public function execute() {
$this->prevLevel = $this->light->getLevel();
$this->light->dim(75);
}
public function undo() {
$this->light->dim($this->prevLevel);
}
}
/** 帶日誌的調用者 **/
class LoggedRemoteControl extends RemoteControl {
private $log = [];
public function pressButton($slot) {
parent::pressButton($slot);
$this->log[] = ["slot" => $slot, "time" => time()];
}
public function getLog() {
return $this->log;
}
}
| 場景 | 命令角色 | 接收者 | 優勢 |
|---|---|---|---|
| GUI 按鈕/選單 | 各功能命令 | 業務服務類 | 解耦 UI 與業務邏輯 |
| 任務佇列/排程 | 可序列化命令物件 | Worker 服務 | 支援延遲執行、重試、持久化 |
| 資料庫遷移 | MigrationCommand | Schema 操作類 | 支援 up/down (rollback) |
| 編輯器操作 | EditCommand (輸入/刪除/格式化) | Document 模型 | 支援 Undo/Redo 堆疊 |
| API 速率限制 | ApiCallCommand | HTTP Client | 佇列化、批次、熔斷 |
php artisan make:job 產生的 Job 類即命令模式,支援佇列、延遲、重試ContainerAwareCommand 實作 CLI 指令