PHP: Creating Dynamic Web Pages with the Composite View Design Pattern

In this fourth part of a series, I demonstrate how to use all the composite view classes defined previously for generating a simple yet dynamic web page using a single rendering method. This example shows the real functionality of the Composite View pattern when it comes to rendering individual web page sections (partials) by using uncluttered, easy-to-follow client code.

Sharing nearly the same logic as its counterpart Composite (at least at a basic level), Composite View is a clever design pattern that takes full advantage of the functionality provided by Composition to manipulate single and multiple elements of a user interface through the same set of methods. While the pattern does work well in a great variety of languages and applications, where it really shines is in the generation of dynamic web pages, especially when implemented within an existing MVC layer, which is very popular these days.

Even though the theoretical concepts that surround the use of Composite View aren’t as easy to follow as the ones that belong to other patterns, the truth is that implementing it with PHP is a fairly straightforward process that can be tackled with only minor hassles. To demonstrate that my claim is true, in previous parts of this series I created a simple hierarchy of composite view classes, comprised first of an abstract parent which defined the structure and behavior of generic view objects, and then of two concrete subclasses for handling multiple and single objects.

Describing the tasks that each of these classes perform is rather pointless; it’s necessary to show how functional they actually are when used in a concrete case. In consonance with this idea, in this penultimate installment of the series I’m going to illustrate how to use the classes for rendering different sections of a basic web page with a single method call. In doing so, you’ll be able to see how powerful the Composite View pattern can be, particularly when it comes to manipulating (X)HTML documents in a truly flexible fashion.

Are you ready to see the set of sample classes developed previously in action? Then keep reading!

Lazy-loading the previous classes: building a basic autoloader

Since my objective here is to demonstrate how to display different sections of a web page by calling only the “render()” method defined by the composite view classes developed in previous tutorials, the first thing that I’m going to do is create a basic autoloader. The autoloader will lazy-load the classes without having to use multiple PHP includes.

Having explained that, here’s the definition of the autoloader. It looks like this:

(Autoloader.php)

<?php

class Autoloader
{
    private static $_instance;
   
    // get the Singleton instance of the autoloader
    public static function getInstance()
    {
       if (!self::$_instance) {
           self::$_instance = new self;
       }
       return self::$_instance;
    }
   
    // private constructor
    private function __construct()
    {
        spl_autoload_register(array($this, ‘load’)); 
    }
   
    // prevent cloning instance of the autoloader
    private function __clone(){}
    
    // autoload classes on demand
    public static function load($class)
    {
        $file = $class . ‘.php’;
        if (!file_exists($file)) {
            throw new ClassNotFoundException(‘The file ‘ . $file . ‘ containing the requested class ‘ . $class . ‘ was not found.’);
        }
        include $file;
        unset($file);
        if (!class_exists($class, FALSE)) {
            throw new ClassNotFoundException(‘The requested class ‘ . $class . ‘ was not found.’);
        }
    }  
}// End Autoloader class

 

<?php

class ClassNotFoundException extends Exception{}

As you can see, the underlying logic of above “Autoloader” class is very simple to grasp. It uses the SPL stack to include a specified class on demand via its static “load()” method. In this case, I decided to implement the autoloader as a Singleton, but naturally this process is entirely optional; it can be tweaked to suit more specific needs.

So far, so good. Now that the previous autoloader is up and running, it’s time to start creating the scenario required to put the previous classes to work together. Given that, in the following segment I’m going to define two basic sections of a fictional web page, together with a master layout. They’ll be rendered on screen by calling a single rendering method.

To see how the web page sections and the corresponding layout will be defined, click on the link that appears below and keep reading.

{mospagebreak title=Creating some web page sections}

As you probably know, dynamic web pages are usually created nowadays by combining different sections, or “partials,” which are rendered individually. Well, in this case this process can be simplified and even taken one step further by using the previous composite view classes. You’re probably wondering how, right? Well, before I answer that question, let me show you the web page sections mentioned in the preceding segment. Here they are:   

(partial1.php)

<div id="top_container">
    <h2>Partial View A</h2>
    <p><?php echo $message;?></p>
</div>


(partial2.php)

<div id="bottom_container">
    <h2>Partial View B</h2>
    <p><?php echo $message;?></p>
</div>
    
As you can see above, the previous web page sections will print a sample message on the browser. In this case they’ve been created in two separate files called “partial1.php” and “partial2.php” respectively. Now, it’s time to define a layout file, which will embed the pertinent sections in a whole web page. Here’s how this layout will look:

(layout.php)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Master Layout</title>
    </head>
    <body>
        <h1>Master Layout</h1>
        <?php echo $content;?>
    </body>
</html>

Frankly speaking, the definition of this layout file is so trivial that it doesn’t bear any further analysis. However, the goal here is to render an entire web page by replacing  the $content variable embedded in the layout with the two partial sections just created. So, the question that comes up is: can this be achieved by using the composite view classes? Fortunately, the answer is a resounding "yes!" as you’ll see when you read the section below.  

Embedding the web page sections into a master layout

If you’re anything like me, you probably want to see if the composite view classes developed previously are really as flexible as they seem to be for rendering (X)HTML templates. Well, to satisfy your curiosity, I suggest you to take a look at the example below. It uses the isolated sections created before for rendering a complete web page:

<?php

try {
    // include the autoloader class and grab an instance of it
    require_once ‘Autoloader.php’;
    $autoloader = Autoloader::getInstance();
   
    // create a partial view using the previous ‘partial1.php’ file
    $partialA = new Partial(‘partial1′);
    $partialA->message = ‘This is a message from partial view A.’;
   
    // create another partial view using the previous ‘partial2.php’ file
    $partialB = new Partial(‘partial2′);
    $partialB->message = ‘This is a message from partial view B.’;
   
    // create a composite View and add the partials to it
    $compositeView = new View(‘layout’);
    echo $compositeView->addView($partialA)
                       ->addView($partialB)
                       ->render();  
}
catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

Didn’t I tell you that it was feasible to create an entire (X)HTML document from top to bottom with a single method call? That’s exactly that the above code sample shows. What’s more, if you test the example by using your own web server, this is the output that you should get:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Master Layout</title>
    </head>
    <body>
        <h1>Master Layout</h1>
        <div id="top_container">
          <h2>Partial View A</h2>
            <p>This is a message from partial view A.</p>
        </div>
        <div id="bottom_container">
            <h2>Partial View B</h2>
            <p>This is a message from partial view B.</p>
        </div>
    </body>
</html>

There you have it. Even though I have to admit that the web page generated above is extremely simple, it’s handy for demonstrating the actual functionality that the Composite View design pattern hides under the hood. As usual, feel free to edit all of the code samples included in this tutorial. Doing so will help you to gain a better understanding of how to use the pattern for manipulating dynamic (X)HTML templates in a truly flexible fashion.

Final thoughts

In this fourth part of the series, things became really interesting (from a practical point of view), since I demonstrated how to use all of the composite view classes defined previously for generating a simple, but dynamic, web page using a single rendering method. This example clearly shows the real functionality of the Composite View pattern when it comes to rendering individual web page sections (partials) by using uncluttered, easy-to-follow client code.

However, we’re not done testing the earlier sample classes. In the final tutorial I’m going to teach you how to utilize them for generating a web page similar to the one that you saw before, but this time by using a two-step rendering process.

Don’t miss the last part!    

Google+ Comments

Google+ Comments