adding the missing classes to show the real purpose of the pattern

This commit is contained in:
Trismegiste
2013-05-11 17:33:47 +02:00
parent cc93827b8f
commit 6f6e86ee48
4 changed files with 89 additions and 19 deletions

View File

@@ -1,6 +1,6 @@
<?php
namespace DesignPatterns;
namespace DesignPatterns\Command;
/**
* Command pattern
@@ -10,7 +10,7 @@ namespace DesignPatterns;
* We have an Invoker and a Receiver. This pattern use a "Command" to delegate the
* method call against the Receiver and use the same method "execute".
* Therefore, the Invoker just know to call "execute" to process the Command of
* the client.
* the client. The Receiver is decoupled from the Invoker
*
* The second aspect of ths pattern is the undo(), which undoes the method execute()
* Command can also be agregated to combine more complex commands with minimum
@@ -23,26 +23,12 @@ namespace DesignPatterns;
* can be implemented with the Command pattern (e.g. vagrant)
*
*/
interface CommandInterface
interface Command
{
/**
* this is the most important method in the Command pattern,
* all config options and parameters should go into the constructor
*
* @return mixed
* The Receiver go in the constructor.
*/
public function execute();
}
class EchoCommand implements CommandInterface
{
public function __construct($what)
{
$this->what = (string)$what;
}
public function execute()
{
echo $this->what;
}
}

30
Command/HelloCommand.php Normal file
View File

@@ -0,0 +1,30 @@
<?php
namespace DesignPatterns\Command;
/**
* This concrete command calls "print" on the Receiver, but an external
* invoker just know he can call "execute"
*/
class HelloCommand implements Command
{
protected $output;
/**
* Each concrete command is builded with different receivers.
* Can be one, many, none or even other Command in parameters
*/
public function __construct(Receiver $console)
{
$this->output = $console;
}
public function execute()
{
// sometimes, there is no receiver and this is the command which
// does all the work
$this->output->write('Hello World');
}
}

34
Command/Invoker.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
/*
* DesignPatternPHP
*/
namespace DesignPatterns\Command;
/**
* Invoker is using the command given to it.
* Example : an Application in SF2
*/
class Invoker
{
protected $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...
*/
public function setCommand(Command $cmd)
{
$this->command = $cmd;
}
public function run()
{
// here is a key feature of the invoker
// the invoker is the same whatever is the command
$this->command->execute();
}
}

20
Command/Receiver.php Normal file
View File

@@ -0,0 +1,20 @@
<?php
/*
* DesignPatternPHP
*/
namespace DesignPatterns\Command;
/**
* Receiver is specific service with its own contract and can be only concrete
*/
class Receiver
{
public function write($str)
{
echo $str;
}
}