Design Patterns PHP - Command Java

1) What have we done?

We just created interface "Command" which deine method "execute"


interface Command
{
    public function execute();
}




We would like to calling "doA" and "doB" log so just created abstract class "LoggerCommand" where we inject "Receiver" and "Logger"


abstract class LoggerCommand implements Command
{
    /**
     * @var Logger
     */
    protected $logger;

    /**
     * @var Receiver
     */
    protected $receiver;

    function __construct(Receiver $receiver, Logger $logger)
    {
        $this->receiver = $receiver;
        $this->logger = $logger;
    }

}




And two concrete classes "LoggerCommandA" and "LoggerCommandB" for log methods respectively "doA" and "doB"


class LoggerCommandA extends LoggerCommand
{
    public function execute()
    {
        $this->receiver->doA();
        $this->logger->log('Class Receiver executed method doA');
    }
}

class LoggerCommandB extends LoggerCommand
{

    public function execute()
    {
        $this->receiver->doB();
        $this->logger->log('Class Receiver executed method doB');
    }
}




2) What really we did?

Instead of direct calling "doA" and "doB" we just call method "execute" on "Command" objects, which by the way of calling proper method also log calling of these methods.


$receiver = new Receiver();
$logger = new Logger();

$commandA = new LoggerCommandA($receiver, $logger);
$commandB = new LoggerCommandB($receiver, $logger);

$commandA->execute();
$commandB->execute();




Now thanks for this pattern we have many pros
- we can create method(like "Command" object" - and later execute it
- we can add there own stuffs - logging, history, undoing
- "Receiver" has stayed untouched