Introducing the Facade Pattern in PHP 5

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’ll certainly agree, pattern-based PHP programming is sometimes a hard-to-master topic. It logically has to be addressed with a considerable level of knowledge (and experience, to be frank), more specifically in those cases where the design pattern to be implemented presents a high grade of abstraction.

Of course, this doesn’t mean that all of the PHP applications that you’re going to develop from this point onward must solve programming-related problems by utilizing a particular pattern. However, learning how to apply different design patterns to tackle common and well-known issues may help to expand your existing background as PHP developer, in addition to improving your overall experience.

Assuming that the previous paragraphs already convinced you that learning pattern-based programming with PHP might be an instructive and educational experience, in this series, which is comprised of two comprehensive articles, I’m going to introduce the foundations of an interesting structural pattern. I’m talking specifically of the facade pattern.

Since I have to admit that this one isn’t very commonly used amid the huge terrain of PHP-based web development, let me first walk you through a brief introduction about what it does. In this way you can anticipate what you’ll learn in the course of these two articles.

To put it simply, the facade pattern can be applied in those situations where you need to create a PHP class which requires the implementation of a complex system as part of one of its methods. At first glance, the previous definition sounds like something applicable in many cases, but the advantage of using a facade schema relies on the point that the class can hide all the logic of the mentioned mechanism, while the mechanism in question knows nothing about the calling class. That sounds pretty good, right?

To clarify the above concepts a bit more, allow me to cite an illustrative example: suppose you have a class which uses a complex set of additional classes to serialize/unserialize different objects before saving them to a database table. In this case, you have a class that hides all the complexity required for serializing the mentioned objects, but there’s also a group of classes that know nothing about the class that called them. As you can see, these classes are only responsible for performing the serialization/unserialization sequence on several objects and nothing else. Period.

Now, are you’re starting to grasp the logic behind the facade pattern? Of course you are!

At this moment , and after explaining a few basic points on how to use the facade pattern with PHP, let’s move forward and learn how all these theoretical concepts can be translated into some functional hands-on examples. Are you ready? Good, let’s get started!

{mospagebreak title=A basic implementation of the facade pattern}

To demonstrate a simple implementation of the facade pattern with PHP 5, what I’ll do first will consist of defining a web page generator class. Later, the class will be capable of hiding all the complexity required for compressing web documents through a set of additional classes, which logically will be completely decoupled from the generator in question. Sounds really simple, doesn’t it?

Now that I’ve explained how I plan to implement the facade pattern with PHP, take a look at the signature of the class below. I named it “WebPage.” Not surprisingly, it is tasked with creating simple (yet dynamic) web documents. Its definition is as follows: 

// define ‘WebPage’ class
class WebPage{
   private $html;
   private $title;
   private $keywords;
   public function __construct($title=’PHP Web
Page’,$keywords=’PHP,Web Development,Object-oriented PHP
       throw new Exception(‘A title for the web page must be
   // create web page header section
   public function makeHeader(){
     $this->html=’<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN" "
xmlns="">’."n".’<head><meta http-
equiv="Content-Type" content="text/html; charset=iso-8859-
1" />’."n".’<meta http-equiv="keywords" content="’.$this-
>keywords.’" />’."n".’<title>’.$this-
   // create web page content section
   public function makeBody($content){
       throw new Exception(‘Content for the web page must be
     $this->html.=’<div id="header"><h2>Header
Section</h2></div>’."n".’<div id="navbar"><h2>Navigation Bar
Section</h2></div>’."n".’<div id="mainsection"><h2>Main
id="footer"><h2>Footer Section</h2></div>’."n";
   // create web page footer section
   public function makeFooter(){
   // get (X)HTML markup
   public function getXHTML(){
     return $this->html;

As you can see, the above web page generator class presents a typical structure for generating the different sections of a web document, that is its header section, then its main area, and finally the corresponding footer.

So far, the logic implemented by the previous class shouldn’t be hard for you to grasp at all. Therefore let me show you a short script which uses the prior class to create a hypothetical web document. The code for this example in particular is as follows:

// example using ‘WebPage’ class
   $webPage=new WebPage(‘This is the sample title for the web
page’,'keyword 1,keyword 2,keyword 3′);
   $webPage->makeBody(‘This is a sample content for the web
   echo $webPage->getXHTML();
catch(Exception $e){
   echo $e->getMessage();

As you may have guessed, using the previously-defined web page generator class is indeed a straightforward process which only requires a minor effort from us. In simple terms, the above script builds a basic web document by calling in turn the “makeHeader(),” “makeBody()” and “makeFooter()” methods, and finally displays it on the browser via “getXHTML().”

At this point, I’m quite sure that you haven’t had major problems understanding how the previous web page generator class works. However, you may be wondering how the facade pattern fit into this schema. Well, let me show you how to create a simple facade class which will be capable of compressing all sorts of strings, including the source code generated by the web page class that you just learned.

Naturally, the signature for this brand new facade class will be shown in the section to come, thus click on the link below and keep reading.

{mospagebreak title=Using HTTP compression with PHP 5}

In consonance with the concepts that I deployed in the section that you just read, the next step that I’m going to take will consist of defining a basic facade class. This class will be capable of applying HTTP compression to any input string, in addition to removing any eventual new line characters from it.

Having outlined the functionality of this simple facade class, please pay attention to its definition. It’s as follows:

// define ‘CompressContentFacade’ class
class CompressContentFacade{
   public static function stripContent($content){
// remove new lines from content
     // compress content by using GZIP algorithm
     return $gzippedContent;

Despite the remarkable simplicity of the above facade class, there are a few things worth stressing about its definition. First, notice how the class in question hides all the complexity required for removing new lines characters and compressing strings behind the interface of two different classes, “StripContent” and “GzipContent” respectively.

Second, you should realize that all of these classes are completely independent from the facade one, which means that they know nothing about the class that called them. If you recall the definition of the facade pattern, this is exactly the schema required for applying it. Now, the prior facade class should make a lot of sense to you!

Nevertheless, I must mention that the previous “CompressContentFacade” class is indeed only half of the story when it comes to implementing the facade pattern with PHP 5, since the corresponding string compressing classes that you saw before remain undefined.

To address this issue, in the following section I’m going to show you the respective signature for these two new classes, in this way completing the model dictated by the facade pattern.

Do you wish to see how these classes will be created? Jump ahead and read the next few lines.

{mospagebreak title=Completing the facade schema}

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/","/
// define ‘GzipContent’ class
class GzipContent{
   // compress content by using GZIP algorithm
   public static function compressString($content){
     echo $content;
     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.

{mospagebreak title=Seeing the facade pattern in action}

As I said before, below I developed a comprehensive example that demonstrates how the facade pattern can be used for compressing the HTTP output of a specific web page, in this case by using all the classes that were created previously. Please take a look at the following code sample:

// example using ‘CompressContentFacade’ class
   // instantiate ‘WebPage’ object
   $webPage=new WebPage(‘This is the sample title for the
compressed web page’,'keyword 1,keyword 2,keyword 3′);
   // create web page header section
   // create web page body section
   $webPage->makeBody(‘This is a sample content for the
compressed web page’);
   // create web page footer section
   // remove new lines and compress web page by using
   // ’CompressContentFacade’ class
   // display compressed web page
   echo $compressedWebPage;
catch(Exception $e){
   echo $e->getMessage();

In the above example, you can see that I first instantiated a new “WebPage” object, then generated the different sections that comprise a sample web document, and finally used the “CompressContentFacade” class to compress the respective HTTP output before sending it straight to the browser.

Do you see how applying the facade pattern with PHP 5 was much simpler that you might have thought? I bet you do!

Final thoughts

Finally, we’ve come to the end of this tutorial. In this first part of the series, I introduced the key points for how to implement the facade pattern with PHP 5 with some illustrative examples.

However, this isn’t the end of this educational journey. In the last installment, I’ll teach you how to use a facade class in conjunction with a file processing application. You won’t want to miss it!

Google+ Comments

Google+ Comments