More Examples of Creating Command Objects with PHP 5

Are you one of those PHP developers who wants to expand your background in design patterns by learning an additional one? If your answer is affirmative, then this series might be appealing to you. It will teach you, in three educational tutorials, how to create and implement command objects with PHP 5.

Frankly speaking, the application of the command pattern with PHP is an accessible topic that seems to be much harder to grasp than what it really is. Essentially, the logic that stands behind the referenced pattern will allow you to establish a carefully-crated relationship between at least two objects, where the first one, usually called the commanded, presents a specific method coded in such a way that it houses all the logic required for being called into another object, in this case named “commander.”

Since the previous definition looks rather difficult to grasp, at least at first glance, the best course of action to take in this case is simply to annex to the corresponding theory into some comprehensive examples. In this way the mentioned pattern can be understood much more clearly, and at the same time, it brings new possibilities for including it into complex applications.

Naturally, in the previous article I followed the learning methodology that I mentioned above by defining some command classes, which were originally capable of instructing a commanded object on how to display a specified input string. Of course, the examples were rather primitive and they should be considered only like that. However, it’s important to mention here that all the code samples that I wrote previously came in really handy for demonstrating by an understandable approach, how to create and use command objects with PHP.

Now, and turning special attention to this second article of the series, I’ll develop a few more hands-on examples concerning the pattern in question, thus you can reaffirm the concepts learned in the preceding installment.

With the theme of this article already established, let’s continue exploring the creation of command objects in PHP 5. Let’s get started!

{mospagebreak title=Building an array command class}

Since creating command classes with PHP is indeed a topic that should be addressed by building several hands-on examples, in this section of the tutorial I’ll begin defining a set of straightforward classes. These classes will be tasked with instructing a commanded object on how to display the elements of a given input array.

Logically, this new group of commanders will expose a common method called “executeCommand()." It will be responsible for performing the conversion of the different elements of the inputted array, in this way composing the first building block of the pattern itself. Naturally, the second block will be made up of the corresponding commanded class, which will be properly defined later on.

For now, I’ll start defining the generic structure of an array command class, which looks like this:

// define abstract 'ArrayCommand' class (the commander)

abstract class ArrayCommand{

	protected $arrayCommanded;

	public function __construct($arrayCommanded){

		$this->arrayCommanded=$arrayCommanded;
	}
	abstract public function executeCommand();
}

If you’ve read the previous tutorial, then you’ll find the signature of the above class quite familiar. Please, notice how this commander accepts an instance of a commanded object as its unique input parameter, and assigns it as a new class property.

Then, there’s the mentioned “executeCommand()” method, which not surprisingly will be charged with instructing the corresponding commanded object on how to display the different elements of a given array. Quite simple, isn’t it?

Now that you hopefully understood how the previous command class was created, let me go one step further and show you the definition of a sub class derived from it. This offers a concrete implementation for the “executeCommand()” method that you saw before.

That said, the signature of this brand new child class is as follows:

// define
concrete 'ArrayToUpperCommand' class (implements concretely the 
'executeCommand()' method class ArrayToUpperCommand extends ArrayCommand{ public function executeCommand(){ $this->arrayCommanded->setUppercasedArray();           } }

As you can see, the above “ArrayToUpperCommand” class presents a concrete definition for the “executeCommand()” method that was defined as abstract previously. More specifically, this method will use an instance of the commanded object to uppercase all the elements of a given input array. This means that, according to the definition of the command pattern, it should encapsulate all the logic necessary for performing the mentioned array processing.

So far, the corresponding definitions for the two previous command classes should give you some clear pointers on how to establish a relationship between a commander and a commanded object. However, my intention here is to show you a couple of additional command classes which logically will instruct the commanded object on how to display different elements of a specified array.

Bearing in mind this possibility for increasing the number of command classes, in the next section I’ll create two additional ones. Therefore you can study (and learn) how a single commanded object can accept instructions from multiple commanders.

The topic sounds really interesting, so go ahead and jump into the next section. I’ll be there, waiting for you.

{mospagebreak title=Creating two more command classes}

As I stated in the previous section, I’d like to extend the initial example by creating two additional command classes. These classes will control programmatically by different methods the way that elements of a specified array are displayed. Keeping in mind this condition, in the following code sample I defined the “ArrayToLowerCommand” and “ArrayToReverse” classes respectively, which not surprisingly will turn into upper cased strings all the elements of an input array, in addition to reversing these elements as well.

Please, take a look at the respective signatures for these new pair of classes:

// define concrete 'ArrayToLowerCommand' class (implements concretely 
the 'executeCommand()' method class ArrayToLowerCommand extends ArrayCommand{ public function executeCommand(){ $this->arrayCommanded->setLowercasedArray();           } } // define concrete 'ArrayToReverseCommand' class (implements concretely
the 'executeCommand()' method class ArrayToReverseCommand extends ArrayCommand{ public function executeCommand(){ $this->arrayCommanded->setReversedArray();    } }

In this case, the two new command classes listed above present signatures that are nearly identical to the previously defined “ArrayToUpperCommand” class. Of course, the only small difference rests on the definition of their respective “executeCommand()” methods, which perform distinct tasks, even when they’re called the same.

Also, it’s important to stress a relevant point with reference to all the command classes: notice how they use an instance of the commanded object to perform well-differentiated processes, but in all the cases, the corresponding methods encapsulate the complete logic for doing their business only into the mentioned commanders. Are you starting to see how this pattern works now? I bet you are.

Okay, at this stage you hopefully understand the principle that stands behind creating all these array command classes, but… what about defining the respective array commanded object?

Fortunately for you and me, the creation of commanded objects is indeed a no-brainer process that can be done with minor hassles, something that I’m going to show you in the next few lines. Therefore, if you’re curious about how these types of objects will be defined, please click on the link below and keep reading.

{mospagebreak title=Building an array commanded class}

To complete the adequate implementation of the command pattern, I need to define another class. This one will be called “ArrayCommanded.” According to the definition of the pattern in question, it will be responsible for encapsulating into different methods all the logic required for manipulating the format of the elements that correspond to an inputted array.

Does this sound a bit confusing? Fear not, because it isn’t. Please, take a look at the signature for this new class to clarify your possible questions:

// define 'ArrayCommanded' class 

class ArrayCommanded{

	private $inputArray;

	public function __construct($inputArray){
		
		$this->setInputArray($inputArray);
	}

	public function setInputArray($inputArray){

		if(!is_array($inputArray)||count($inputArray)<1){

			throw new Exception('Input data must be a 
non-empty array!');                         }                         $this->inputArray=$inputArray; } public function getinputArray(){ return $this->inputArray; } // uppercase input array (encapsulates all the logic to execute
the method in the command object) public function setUppercasedArray(){ $this->setinputArray(array_map('strtoupper',$this->
getInputArray())); } // lowercase input array (encapsulates all the logic to execute
the method in the command object) public function setLowercasedArray(){ $this->setinputArray(array_map('strtolower',
$this->getInputArray())); } // reverse input array (encapsulates all the logic to execute
the method in the command object) public function setReversedArray(){ $this->setinputArray(array_reverse($this->
getInputArray())); } }

As I said previously, the above “ArrayCommanded” class presents all the required methods. This is useful for processing the format that corresponds to the elements of the “$inputArray” array. Even when the logic implemented by the referenced methods is very easy to follow, it demonstrates in a clear fashion how a single commanded class can be constructed in such a way that it can accept instructions from different commanders. Isn’t this great?

All right, now that you’ve learned how the commanders were appropriately created, in conjunction with defining their corresponding commanded class, it’s time to move forward and tackle the last section of this article. I will show you how all these classes can work together; in short, you’ll see the commander pattern in action.

{mospagebreak title=Including all the classes in one hands-on example}

To show you how all the previously defined classes can be integrated into the same code sample, below I set up a simple yet illustrative script. It shows the neat functionality of the command pattern by using both the commanders and commanded objects that you learned before. Here is the mentioned script, along with its respective outputs:

try{
	// instantiate 'ArrayCommanded' object

	$arrayCommanded=new ArrayCommanded(array('Element 1',
'Element 2','Element 3','Element 4','Element 5')); // display input array after instantiating 'ArrayCommanded'
object print_r($arrayCommanded->getInputArray()); /* displays the following    Array ( [0] => Element 1 [1] => Element 2 [2] => Element 3 [3]
=> Element 4 [4] => Element 5 )            */ // instantiate 'ArrayToUpperCommand' object $arrayToUp=new ArrayToUpperCommand($arrayCommanded); // execute 'setUppercasedArray()' method $arrayToUp->executeCommand(); // displays input array after executing the method print_r($arrayCommanded->getInputArray()); /* displays the following:            Array ( [0] => ELEMENT 1 [1] => ELEMENT 2 [2] => ELEMENT 3 [3]
=> ELEMENT 4 [4] => ELEMENT 5 ) */ // instantiate 'ArrayToLowerCommand' object $arrayToLow=new ArrayToLowerCommand($arrayCommanded); // execute 'setLowercasedArray()' method $arrayToLow->executeCommand(); // displays input array after executing the method print_r($arrayCommanded->getInputArray()); /* displays the following: Array ( [0] => element 1 [1] => element 2 [2] => element 3
[3] => element 4 [4] => element 5 ) */ // instantiate 'ArrayToReverseCommand' object $arrayToRev=new ArrayToReverseCommand($arrayCommanded); // execute 'setReversedArray()' method $arrayToRev->executeCommand(); // displays data string after executing the method print_r($arrayCommanded->getInputArray()); /* displays the following:         Array ( [0] => element 5 [1] => element 4 [2] => element 3 [3]
=> element 2 [4] => element 1 ) */ } catch(Exception $e){             echo $e->getMessage();             exit(); }

As you can see, the above example illustrates clearly how the command pattern can be applied by utilizing all the previously created classes. In addition, the prior script also displays the corresponding array elements according to the “array command” applied to them via the respective “ArrayCommanded” class.

As usual, feel free to tweak the source code of all the classes shown in this article. You can experiment with them and introduce your own approaches for implementing this handy pattern.

Final thoughts

That’s all for the moment. In this second part of the series, I extended the application of the command pattern by defining some array processing classes, which came in very handy for demonstrating the functionality of the pattern in question.

However, this journey isn’t finished yet. In the last tutorial, I’ll show you how to apply the command pattern in a more useful fashion. You’ll learn how to use it to work with self-saving objects. I’ll meet you there!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort