HomePHP Page 3 - Introduction to Creating Command Objects with PHP 5
Creating additional command classes - PHP
In this article, the first part of a series, you'll learn the basics of applying the command pattern with PHP 5. As always, plenty of hands-on examples are included.
As you learned in the previous section, the command class, called "StringToUpperCommand," was responsible for executing the corresponding "setUppercasedString()" method, in this case provided by the commanded object. This fact demonstrates, in a clear way, the structure of the command pattern, since the method I mentioned previously houses all the logic required to be called into the pertinent command class.
However, as you saw previously, the command class that I just defined is capable of instructing the commanded object to uppercase a specified input string. Therefore, and considering the intrinsic versatility of the command pattern, I'm going to create a few additional command classes, so that you can understand how one single commanded object can receive "orders" from different commanders. That would definitely be interesting, right?
Okay, that being said, below I coded a couple of extra command classes. These classes are tasked with upper-casing and reversing a given string in the commanded object via their corresponding "executeCommand()" methods. The signatures for these brand new classes are as follows:
// define concrete 'StringToLowerCommand' class (implements concretely
the 'executeCommand()'method
class StringToLowerCommand extends DataCommand{
public function executeCommand(){
$this->dataCommanded->setLowercasedString();
}
}
// define concrete 'StringToReverseCommand' class (implements concretely
the 'executeCommand()'method
class StringToReverseCommand extends DataCommand{
public function executeCommand(){
$this->dataCommanded->setReversedString();
}
}
As you'll possibly realize, the two command classes defined above are very similar to the first one that I coded in the previous section. Naturally, the only difference to spot here is the implementation of each of their "executeCommand()" methods, which are responsible for upper-casing and reversing a given input string into the corresponding $dataCommanded object.
At this point, and after defining the three previous command classes, it's time to move forward and learn how to create the long awaited commanded class, since I haven't shown how it will look.
In the next few lines I'll demonstrate how to define this relevant class, therefore if you're interested in learning how this process will be achieved, click on the link that appears below and keep reading.