HomePHP Page 4 - More Examples of Creating Command Objects with PHP 5
Building an array commanded class - PHP
Are you one of those PHP developers who wants to expand your background in design patterns by learning an additional one? If your answer is affirmative, then this series might be appealing to you. It will teach you, in three educational tutorials, how to create and implement command objects with PHP 5.
To complete the adequate implementation of the command pattern, I need to define another class. This one will be called "ArrayCommanded." According to the definition of the pattern in question, it will be responsible for encapsulating into different methods all the logic required for manipulating the format of the elements that correspond to an inputted array.
Does this sound a bit confusing? Fear not, because it isn't. Please, take a look at the signature for this new class to clarify your possible questions:
// define 'ArrayCommanded' class
class ArrayCommanded{
private $inputArray;
public function __construct($inputArray){
$this->setInputArray($inputArray);
}
public function setInputArray($inputArray){
if(!is_array($inputArray)||count($inputArray)<1){
throw new Exception('Input data must be a
non-empty array!');
}
$this->inputArray=$inputArray;
}
public function getinputArray(){
return $this->inputArray;
}
// uppercase input array (encapsulates all the logic to execute
the method in the command object)
public function setUppercasedArray(){
$this->setinputArray(array_map('strtoupper',$this->
getInputArray()));
}
// lowercase input array (encapsulates all the logic to execute
the method in the command object)
public function setLowercasedArray(){
$this->setinputArray(array_map('strtolower',
$this->getInputArray()));
}
// reverse input array (encapsulates all the logic to execute
the method in the command object)
public function setReversedArray(){
$this->setinputArray(array_reverse($this->
getInputArray()));
}
}
As I said previously, the above "ArrayCommanded" class presents all the required methods. This is useful for processing the format that corresponds to the elements of the "$inputArray" array. Even when the logic implemented by the referenced methods is very easy to follow, it demonstrates in a clear fashion how a single commanded class can be constructed in such a way that it can accept instructions from different commanders. Isn't this great?
All right, now that you've learned how the commanders were appropriately created, in conjunction with defining their corresponding commanded class, it's time to move forward and tackle the last section of this article. I will show you how all these classes can work together; in short, you'll see the commander pattern in action.