Handling File Data with the Facade Pattern in PHP 5 - Applying the facade pattern to a string processor
(Page 3 of 4 )
Undoubtedly, one of the best ways to understand more clearly the logic that belongs to the facade pattern consists of defining a class that implements the referenced pattern in a friendly format. In this case, I followed this approach faithfully, and created the class below. It is named “ProcessContentFacade,” and its signature is as follows:
// define 'ProcessContentFacade' class
class ProcessContentFacade{
public static function processContent($content){
// reverse content
$reversedContent=StringToReverse::reverseString($content);
// uppercase content
$uppercasedContent=StringToUppercase::
uppercaseString($reversedContent);
return $uppercasedContent;
}
}
As you’ll realize, the previous facade class is capable of performing a few handy formatting tasks, like uppercasing and reversing a given input string in turn. However, the most remarkable aspect concerning the signature of this class rests on the approach followed for executing these operations. They’re performed by using two additional classes, called “StringToReverse” and “StringToUppercase” respectively.
The corresponding definitions for these additional classes are shown below. Please take a look at them:
// define 'StringToReverse' class
class StringToReverse{
// reverse string
public static function reverseString($inputString){
if(!$inputString){
throw new Exception('Input string must not be empty!');
}
return strrev($inputString);
}
}
// define 'StringToUppercase' class
class StringToUppercase{
// uppercase string
public static function uppercaseString($inputString){
if(!$inputString){
throw new Exception('Input string must not be empty!');
}
return strtoupper($inputString);
}
}
Here, it’s clear to see how the facade pattern is appropriately implemented: on one hand you have a specific class that hides the process for reversing and uppercasing an inputted string; on the other hand, there are two classes that are completely independent from each other, and besides, they don’t know anything about the class that called them. Is this a programmatic model of the facade pattern? Of course it is!
Okay, I have to admit that I got caught up for a moment. But seriously, the three classes that you saw before demonstrate how easy it is to implement the facade pattern with PHP 5.
Now that you have properly grasped the logic followed by this group of classes, it’s time to move forward. We'll see how the file processor that I built in the beginning of this article can be incorporated into one single example. In this way we'll complete the implementation of the facade pattern.
As you can see, all the pieces of this puzzle are starting to fit together. If you want to see how this journey ends, click on the link below and read the final section of this tutorial. We’re almost done!
Next: Putting all the classes to work together >>
More PHP Articles
More By Alejandro Gervasio