{
    "slug": "command_pattern",
    "term": "Command Pattern",
    "category": "quality",
    "difficulty": "intermediate",
    "short": "Encapsulates a request as an object, enabling queuing, logging, undo/redo, and decoupling of request sender from receiver.",
    "long": "The Command pattern wraps a request — with all its parameters — as an object implementing a common execute() interface. The invoker (controller, queue worker) knows only the Command interface; the receiver (domain service) knows nothing about the invoker. This enables: queuing and deferred execution, logging all executed commands for audit, undo/redo by implementing an unexecute() method, and macro commands (composites of commands). In PHP, the Command Bus pattern (used in CQRS frameworks like Tactician and Laravel's Command Bus) dispatches command objects to dedicated handler classes.",
    "aliases": [
        "command object",
        "action pattern",
        "encapsulated request"
    ],
    "tags": [
        "design-pattern",
        "oop",
        "behavioural"
    ],
    "misconception": "The command pattern is only useful for undo/redo functionality. Commands also enable queuing, logging, macro recording, transactional operations, and decoupling the sender of a request from its executor.",
    "why_it_matters": "The Command pattern encapsulates a request as an object — enabling queuing, logging, undo/redo, and retry without coupling the invoker to the specific operation being performed.",
    "common_mistakes": [
        "Implementing Command without an undo() method when reversibility is a requirement — retrofitting it later is expensive.",
        "Commands that access external services directly instead of through injected dependencies — makes testing hard.",
        "Using a command bus for simple CRUD with no queue, audit, or retry requirement — overkill that adds complexity.",
        "Not making commands serializable when they need to be queued or persisted — use value types, not service references."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "cqrs",
        "command_query_separation",
        "strategy_pattern"
    ],
    "prerequisites": [
        "interfaces",
        "queue_based_load_levelling",
        "message_queue_patterns"
    ],
    "refs": [
        "https://refactoring.guru/design-patterns/command"
    ],
    "bad_code": "// Direct invocation instead of command — no queuing, logging, or undo:\nclass OrderController {\n    public function cancel(int $id): void {\n        $order = Order::find($id);\n        $order->status = 'cancelled'; // Logic scattered, no audit trail\n        $order->save();\n    }\n}",
    "good_code": "interface Command {\n    public function execute(): void;\n    public function undo(): void;\n}\n\nclass MoveFileCommand implements Command {\n    public function __construct(\n        private string $from,\n        private string $to,\n    ) {}\n    public function execute(): void { rename($this->from, $this->to); }\n    public function undo(): void    { rename($this->to, $this->from); }\n}\n\nclass CommandHistory {\n    private array $stack = [];\n    public function execute(Command $cmd): void {\n        $cmd->execute();\n        $this->stack[] = $cmd;\n    }\n    public function undo(): void {\n        array_pop($this->stack)?->undo();\n    }\n}",
    "quick_fix": "Encapsulate a request as a Command object with a handle() method — this enables queuing, logging, undo, and retry without changing the invoker",
    "severity": "low",
    "effort": "medium",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/command_pattern",
        "html_url": "https://codeclaritylab.com/glossary/command_pattern",
        "json_url": "https://codeclaritylab.com/glossary/command_pattern.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Command Pattern](https://codeclaritylab.com/glossary/command_pattern) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/command_pattern"
            }
        }
    }
}