HomePHP Page 4 - Introducing the Facade Pattern in PHP 5
Completing the facade schema - PHP
The facade pattern may be one of the less well known patterns in PHP, but it definitely has its uses. In this first article of a two-part series, you'll learn the basics of how the facade pattern works, illustrated with numerous examples.
As you learned in the previous section, there are still two classes whose signatures weren’t shown yet. They are necessary for completing the programmatic model imposed by the facade pattern. Below I listed the respective definitions for this pair of additional classes. They are tasked with removing new line characters from a given string, and compressing the string via the GZIP algorithm.
That being said, the signatures for the classes in question look like this:
// define 'StripContent' class class StripContent{ // remove new lines from content public static function stripString($content){ return preg_replace(array("/r/","/n/","/ rn/"),'',$content); } } // define 'GzipContent' class class GzipContent{ // compress content by using GZIP algorithm public static function compressString($content){ ob_start(); echo $content; $content=gzencode(ob_get_clean(),9); header('Content-Encoding: gzip'); return $content; } }
As you can see, each of the above classes does its business by calling a single static method. Of course, I decided to define these methods that way, thus they’re callable from outside any object context, but this condition can be easily changed to suit your personal requirements.
Okay, at this stage hopefully you learned the logic that stands behind the facade pattern. After all, on one hand I created a facade class which hides all the complexity required for compressing content, while on the other hand there are two independent classes that know nothing about the facade. Pretty simple, right?
However, there’s still a missing piece here concerning the implementation of the “WebPage” class that I defined in the beginning of this article. In the final section of this tutorial, I’ll show you how to integrate the previous facade class, along with the mentioned web page generator, to compress different web documents.
This interesting example will be set up in the following section, therefore if you want to learn more about it, please click the link below and keep reading.