Using Self-Saving Objects with Command Objects in PHP 5

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.

Certainly, one of the things that you’ll surely recall from the preceding article is the fact that implementing the command pattern with PHP is a quite straightforward process which can be carried out with minor problems. As you learned before, the procedure is only limited to defining a specific class, dubbed “commanded,” which will expose a method capable of encapsulating all the logic required for execution in another object. Lastly, this second object involved in the relationship is called a “commander,” and it will take care of invoking the mentioned method inside of its own scope. That’s fairly understandable, right?

Of course, one of the best courses of action to take when it comes to explaining the logic that stands behind the command pattern is to develop some concrete examples. In this way you can see how these objects interact with each other, as well as the neat functionality of this pattern.

Now, and focusing my attention specifically on the topics that I plan to discuss in this final part of the series, I’m going to extend the creation and use of command objects to use the pattern in a more helpful fashion. Essentially, I’m going to explain how to utilize command classes for defining and handling self-saving objects, that is objects capable of storing a copy of themselves on a database, text file, etc.

By doing so, I’ll give you a much clearer idea of how the command pattern can be used in real-world applications, and at the same time you’ll expand your existing background in using design patterns with PHP 5 as well.

With the preliminaries out of our way, it’s time to find out together how to use commanders in the creation of self-saving objects. The experience will be really educational, so let’s get started!

{mospagebreak title=Defining a core module of the command pattern}

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){

	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.

{mospagebreak title=Storing and loading self-saving objects}

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.

{mospagebreak title=Completing the command pattern}

In consonance with the concepts that I deployed a few lines above, the only piece that remains still undefined is the class that creates commanded objects. In this particular case, a commanded object must expose two concrete methods, called “save()” and load()” respectively, which will perform the saving and loading operations on the object itself.

Perhaps the previous definition sounds a little bit confusing, but in fact any possible doubts that you may have will be clarified if you take a look at the signature of the mentioned commanded class. Following only my common sense, I called this class “ObjectCommanded,” and its source code is as follows:

// define 'ObjectCommanded'class

class ObjectCommanded{

	private $objectPath;

	public function __construct($objectPath){


	public function setObjectPath($objectPath){


			throw new Exception('Invalid target file to 
save object!'); } $this->objectPath=$objectPath; } // auto save commanded object public function save(){ if(!$fp=fopen($this->objectPath,'w')){ throw new Exception('Error opening target
file!');                 }                 if(!fwrite($fp,serialize($this))){ throw new Exception('Error writing target
file!'); } fclose($fp); } // auto load commanded object public function load(){ if(!$obj=unserialize(file_get_contents
($this->objectPath))){ throw new Exception('Error loading object
from target file!'); } return $obj; } }

If you examine the above class, you’ll grasp quickly what it does. As you can see, this “ObjectCommanded” class is capable of saving an instance of itself to a given text file, aside from loading this instance from the mentioned file. All these processes are performed via a serialization-unserialization sequence, something that is clearly demonstrated by the definition of the corresponding “load()” and “save()” methods.

Nevertheless, the most interesting aspect concerning the implementation of these methods has to do with the intrinsic definition for the command pattern, since they encapsulate all the logic necessary for execution in the respective commanders. Now, do you see how a self-saving object can be programmatically instructed by the two previous command classes? I guess you do!

All right, at this point you hopefully learned not only how the object command classes were properly defined, but how the respective commanded class was created too. Thus, with all these elements at our disposal, certainly it’d be very instructive if we can develop a practical example that integrates all the pieces together, implementing the already familiar command pattern.

That’s exactly what I’m going to do in the final section of this article, therefore I suggest you click on the below link and keep reading.

{mospagebreak title=Seeing the command pattern in action}

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

	$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!

Google+ Comments

Google+ Comments