HomePHP Page 3 - Using Self-Saving Objects with Command Objects in PHP 5
Storing and loading self-saving objects - 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.
As I stated in the previous section, the next step that I’m going to take to apply the command pattern will involve deriving two child classes from the parent “ObjectComand.” In simple words, the tasks performed by these two classes will consist of instructing the commanded object about saving and loading itself from a given text file.
That being said, here are the signatures for these child command classes. Take a look at them, please:
// define concrete 'SaveObjectCommand' class (implements concretely the
'executeCommand()' method
class SaveObjectCommand extends ObjectCommand{
public function executeCommand(){
$this->objectCommanded->save();
}
}
// define concrete 'LoadObjectCommand'class (implements concretely the
'executeCommand()' method
class LoadObjectCommand extends ObjectCommand{
public function executeCommand(){
return $this->objectCommanded->load();
}
}
Definitely, after seeing the source code that corresponds to the pair of command classes listed above, you’ll have to agree with me that they’re actually very simple, but at the same time quite powerful.
Please notice how each one of their “executeCommand()” methods uses an instance of the commanded object to call “save()” and “load()” respectively. From examining only these two methods, it’s clear to see how a commanded object is capable of housing all the programming logic required for execution in the pertinent commanders. Undoubtedly, this kind of relationship between classes shows in a nutshell how the commander pattern can be easily implemented with self-saving objects. Pretty good, right?
So far, so good. At this point, you learned the corresponding definitions for the two object command classes that were shown before. However, there’s still a missing piece concerning this schema, since the respective commanded object hasn’t been defined yet.
Therefore, in the next few lines I’m going to show how to create a self-saving commanded object which will complete the implementation for the already popular command pattern.
As usual, if you want to learn how this commanded class will be created, read the following section.