interfaceCommand { /** * this is the most important method in the Command pattern, * The Receiver goes in the constructor. */ publicfunctionexecute(); }
UndoableCommand.php
1 2 3 4 5 6 7 8 9 10 11
<?phpdeclare(strict_types = 1);
namespaceDesignPatterns\Behavioral\Command;
interfaceUndoableCommandextendsCommand { /** * This method is used to undo change made by command execution */ publicfunctionundo(); }
/** * This concrete command calls "print" on the Receiver, but an external * invoker just knows that it can call "execute" */ classHelloCommandimplementsCommand { private Receiver $output;
/** * Each concrete command is built with different receivers. * There can be one, many or completely no receivers, but there can be other commands in the parameters */ publicfunction__construct(Receiver $console) { $this->output = $console; }
/** * execute and output "Hello World". */ publicfunctionexecute() { // sometimes, there is no receiver and this is the command which does all the work $this->output->write('Hello World'); } }
/** * This concrete command tweaks receiver to add current date to messages * invoker just knows that it can call "execute" */ classAddMessageDateCommandimplementsUndoableCommand { private Receiver $output;
/** * Each concrete command is built with different receivers. * There can be one, many or completely no receivers, but there can be other commands in the parameters. */ publicfunction__construct(Receiver $console) { $this->output = $console; }
/** * Execute and make receiver to enable displaying messages date. */ publicfunctionexecute() { // sometimes, there is no receiver and this is the command which // does all the work $this->output->enableDate(); }
/** * Undo the command and make receiver to disable displaying messages date. */ publicfunctionundo() { // sometimes, there is no receiver and this is the command which // does all the work $this->output->disableDate(); } }
/** * Invoker is using the command given to it. * Example : an Application in SF2. */ classInvoker { private Command $command;
/** * in the invoker we find this kind of method for subscribing the command * There can be also a stack, a list, a fixed set ... */ publicfunctionsetCommand(Command $cmd) { $this->command = $cmd; }
/** * executes the command; the invoker is the same whatever is the command */ publicfunctionrun() { $this->command->execute(); } }