HomePHP Page 5 - Using Self-Saving Objects with Command Objects in PHP 5
Seeing the command pattern in action - 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 expressed earlier, to see how the previously defined command classes along with the respective commanded object can be put to work together, it’s necessary to prepare a practical example where all the pieces fit together.
Given that, below I coded a simple script. It shows clearly how the two object commanders are capable of instructing the commanded class on when to save an instance of itself to a specified text file, as well as when to perform an auto-loading process. Have a look at the following code sample, please:
// instantiate 'ObjectCommanded' object
// instantiate 'SaveObjectCommand' object
// execute 'save()' method in commanded object (commanded
object is saved to target file)
// instantiate 'LoadObjectCommand' object
// execute 'load()' method in commanded object (commanded
object is loaded from target file)
As shown above, after instantiating the corresponding commanded object, the two “SaveObjectCommand” and “LoadObjectCommand” commanders simply invoke their “executeCommand()” methods, which trigger the respective auto-saving and auto-loading operations in the object in question.
In addition, I strongly recommend that you experiment with all the classes that were developed in this article so that you can acquire a more solid background in how to apply the command pattern within your own PHP applications.
Sadly, we’ve come to the end of this series. However, I hope this journey has been instructive, particularly if you’re interested in expanding your skills in the terrain of pattern-based PHP programming. More specifically, if the command pattern that you learned here has caught your attention, don’t hesitate to use it in your future projects. See you in the next PHP tutorial!