Command
8/8/25Less than 1 minute
Description
Command is behavioral design pattern that converts requests or simple operations into objects.
- Chuyển request thành object
Example
Xử lí lưu post với các trạng thái yêu cầu là draft, no approval, pusblish,..
Class xử lí business logic cho post:
class PostReceiver { public function draft() { // do something } public function noApproval() { // do something } public function publish() { // do something } }
Command:
interface Command { public function excute(); }
Concreate command: class implement command define thực thi của Receiver tương ứng với case request.
class DraftCommand implements Command { protected PostReceiver $receiver; public function __construct(PostReceiver $receiver) { $this->receiver = $receiver; } public function execute() { $this->receiver->saveDraft(); } }
class NoApprovalCommand implements Command { protected PostReceiver $receiver; public function __construct(PostReceiver $receiver) { $this->receiver = $receiver; } public function execute() { $this->receiver->saveNoApproval(); } }
class PublishCommand implements Command { protected PostReceiver $receiver; public function __construct(PostReceiver $receiver) { $this->receiver = $receiver; } public function execute() { $this->receiver->savePublish(); } }
Invoker: Liên kết với command, gửi request đến command.
class Invoker { private Command $command; public function setCommand(Command $cmd) { $this->command = $cmd; } public function run() { $this->command->execute(); } }
Usage:
$invoker = new Invoker(); $postReceiver = new PostReceiver(); $invoker->setCommand(new DraftCommand($postReceiver)); $invoker->run();
→ Dễ dàng thêm các command mới mà vẫn tuân thủ Open/Closed Principle .
→ Dễ thực hiện unit testing.