HomePHP Page 2 - Using Self-Saving Objects with Command Objects in PHP 5
Defining a core module of the command pattern - PHP
If you were looking for an approachable guide on how to create and use command objects with PHP 5, then look no further, because your search is over. Welcome to the final part of the series “Creating command objects with PHP 5.” Comprised of three comprehensive tutorials, this series walks you through the basics of how to apply the command pattern in PHP, and it accompanies its corresponding theory with numerous code samples.
In order to start developing the final example included in this series, I’ll define an object command class. As you may guess, this class will be tasked with sending two specific orders to the commanded object, implemented via a couple of straightforward methods. The first method will instruct the commanded to save itself to a text file, while the second method will indicate that the object in question must be loaded from that file.
Having explained the functionality that I plan to give to commander and commanded objects respectively, I’ll begin listing the generic definition for this object command class. Its signature is the following:
// define abstract 'ObjectCommand' class (the commander)
abstract class ObjectCommand{
protected $objectCommanded;
public function __construct($objectCommanded){
$this->objectCommanded=$objectCommanded;
}
abstract public function executeCommand();
}
As you can see, the object command class listed above accepts an instance of the respective commanded, which is directly assigned as a new data member. In addition, you can appreciate that there’s an abstract method which is called “executeCommand().”
Logically, after giving a concrete implementation for the previous method, the command class will be capable of instructing the commanded object to save itself to a given text file, or perform an auto-loading process from the mentioned file.
Now, having defined the general structure for the corresponding command class, come with me and visit the following section. You’ll learn how to derive two concrete classes from the respective parent to implement the pertinent “save()” and “load()” instructions on a commanded object via the previously created “executeCommand()” method.
To see how these brand new command classes will be properly defined, please read the following section.