What is the Command pattern and command bus in PHP?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized PHP deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
The Command pattern encapsulates a request as a standalone object containing all the information needed to perform the action. This allows parameterizing clients with different requests, queuing or logging requests, and supporting undo operations. In PHP, a command is a simple DTO: class CreateUserCommand { public function __construct(public readonly string $name, public readonly string $email) {} }. A Command Bus routes commands to their handlers: $bus->dispatch(new CreateUserCommand("Alice", "alice@example.com")) finds and calls the corresponding CreateUserHandler::handle(). This decouples the caller from the handler, makes operations testable in isolation, enables middleware (logging, transactions, authorization) around any command, and supports async execution by pushing commands onto a queue. Libraries like Tactician provide a simple command bus, while Laravel's Job system implements a variant of this pattern.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What is the PHP Event Loop concept with ReactPHP?
Next
What are PHP design patterns for solving common problems?