Using Self-Saving Objects with Command Objects in PHP 5 - Seeing the command pattern in action
(Page 5 of 5 )
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:
try{
// instantiate 'ObjectCommanded' object
$objCom=new ObjectCommanded('default_path/object.txt');
// instantiate 'SaveObjectCommand' object
$saveObjCom=new SaveObjectCommand($objCom);
// execute 'save()' method in commanded object (commanded
object is saved to target file)
$saveObjCom->executeCommand();
// instantiate 'LoadObjectCommand' object
$loadObjCom=new LoadObjectCommand($objCom);
// execute 'load()' method in commanded object (commanded
object is loaded from target file)
$loadedObj=$loadObjCom->executeCommand();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
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.
Final thoughts
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!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |