首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

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

     編輯:PHP 綜合知識

命令模式在 PHP 中的實作與應用

命令模式將「請求」封裝為物件,從而使您可用不同的請求對客戶進行參數化、對請求排隊或記錄請求日誌、支援可撤銷操作。本文提供完整 PHP 實作與實用場景。

核心角色

  1. Command (命令介面):宣告 execute() 方法
  2. ConcreteCommand (具體命令):綁定接收者與動作,實作 execute()
  3. Receiver (接收者):執行實際業務邏輯
  4. Invoker (請求者/調用者):持有命令物件,觸發 execute()
  5. Client (客戶端):建立命令、設定接收者、指派給調用者

完整 PHP 實作

<?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 服務支援延遲執行、重試、持久化
資料庫遷移MigrationCommandSchema 操作類支援 up/down (rollback)
編輯器操作EditCommand (輸入/刪除/格式化)Document 模型支援 Undo/Redo 堆疊
API 速率限制ApiCallCommandHTTP Client佇列化、批次、熔斷

Laravel/Symfony 中的命令模式應用

  • Laravel Job/Command:php artisan make:job 產生的 Job 類即命令模式,支援佇列、延遲、重試
  • Symfony Command:ContainerAwareCommand 實作 CLI 指令
  • Event Sourcing:事件即命令,儲存事件流而非當前狀態

何時使用命令模式

  • ✅ 需要將請求參數化、排隊、記錄日誌
  • ✅ 需要支援撤銷/重做
  • ✅ 需要解耦調用者與接收者
  • ❌ 簡單直接的呼叫關係(過度設計)
  • ❌ 命令極少且固定不變
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved