Application of command mode in php design mode

  • 2020-06-01 09:19:20
  • OfStack

Command mode: encapsulate one request into one object, so you can parameterize the customer with different requests. Queue or log requests to requests, and support revocable operations.
Command:
1. Command role: declares an abstract interface to all concrete command classes. This is an abstract role.
2. Specific command role: define a weak coupling between the receiver and the behavior; Implement the execute method, which is responsible for calling the appropriate operations accepted. The execute() method is usually called the execute method
3. Customer role: create a specific command object and determine its recipient.
4. Requester role: responsible for calling the command object to execute the request. The related methods are called action methods.
5. Recipient role: responsible for the specific implementation and execution of a request.
Function:
1. Abstract the action to be executed to parameterize the object.
2. Specify, arrange, and execute requests at different times.
3. Support cancel operations
4. Support modify log


<?php
// The command interface 
interface Command{
     public function execute();
}
// Specific commands 
class ConcreteCommand implements Command{
     private $_receiver;
     public function __construct($receiver){
          $this->_receiver = $receiver;
     }
     public function execute(){
          $this->_receiver->action();
     }
}

// The recipient 
class Receiver{
     private $_name;
     public function __construct($name){
          $this->_name = $name;
     }
     // Action method 
     public function action(){
          echo $this->_name.'do action .<br/>';
     }
}
// The requester 
class Invoker{
     private $_command;
     public function __construct($command){
          $this->_command = $command;
     }
     public function action(){
          $this->_command->execute();
     }
}

// The client 
class  Client{
     public static function main(){
          $receiver = new Receiver('jaky');
          $command = new ConcreteeCommand($receiver);
          $invoker = new Invoker($command);
          $invoker->action();
     }
}
Client::main();
?>


Related articles: