Monthly Archive for September, 2013

The Composite Design Pattern in PHP: Part II Composing with Images

cornerDon’t forget to Program to the Interface!

While the primary principle we draw from the Composite pattern is , Favor object composition over class inheritance, as discussed in Part I of the Composite series, another important principle applies here as well. The very first principle of design patterns is, Program to an interface, not an implementation. In a sense this is saying, program to an abstract parent and not a concrete child, but if you understand an interface to be the structure implied in either an interface (as used in the first and in this example) or an abstract class, you can see what the value of that principle is.

In this part, instead of a single leaf and a hierarchy rending output, this example shows how a Composite design with multiple leaves can be used to create a mosaic—which is the essence of composite! The interface (IComponent) is little changed except the string parameter has been removed from the operation() method and replaced (for clarity) with a method named showPix() with no parameters. All of the other methods remain the same. Play the application and download the source code and files to get started:
PlayDownload

Follow the Structure; Not the Sequence

To get out of the tar pit of sequential programming, look at the structure and think in terms of using larger structural concepts. Take a look at the three key participants in the Composite pattern, beginning with the key structural participant, the IComponent interface, focusing on their structure as outlined in the interface.


//IComponent.php
interface IComponent
{
    public function showPix();
    public function add(IComponent $comOn);
    public function remove(IComponent $comGone);
    public function getChild($someInt);
}
?>

As in Part I, the IComponent has four methods to be implemented, and though all four are implemented, only the first two are used for this second part. The focus is still on the idea of composition. The fact that we don’t need the second two right now does not detract from the fact that they (remove() and getChild() methods) unimportant for the pattern; just not for this example.

So the implementation of the the Composite class looks structurally similar to that in Part I, but the constructor function has no node name to identify in a parameter. Likewise, the showPix() method is almost identical to the operation() method in Part I, and only the name of the array has changed from $aChildren to $mosaic. Also, the echo statement is no longer part of the method.


//Composite.php
class Composite implements IComponent
{
    private $mosaic;
 
    public function __construct()
    { 
        $this->mosaic=array();
    }
 
    public function add(IComponent $comOn)
    {
        array_push($this->mosaic,$comOn);
    }
 
    public function remove(IComponent $comGone)
    {
        //Code to remove component
    }
 
    public function getChild($someInt)
    {
        //Code to get child by element value
    }
 
    //Note: The following method is recursive
    public function showPix()
    {
        foreach($this->mosaic as $tile)
        {
            $tile->showPix();
        }
    }
}
?>

If you’ve played both Part I and Part II examples of Composite patterns, you know they are very different in what they generate, but the structures for both are virtually identical. Each is combining leaf elements into composite ones. Same structure; different outcomes. That virtually defines code re-use.

Parts is Parts

While the implementation of the Composite class is little unchanged, the number and implementation of the leaf nodes are different. Each leaf class has a single task and no constructor parameter. The unused methods are implemented the same. Each leaf contains an HTML tag to an image. The Composite class stores instances of leaf instances in the $mosaic array and creates rows of images that are aligned to display the tiled image. You can think of each tile in the display as a leaf, and each row a composite of tiles and the entire mosaic as a composite of the three composites that make up the rows.


class Leafr1c1 implements IComponent
{   
    /* None of this batch of methods are used by leaf participants */
    /* However in order to correctly implement the interface */
    /* you need some kind of implementation */
    public function add(IComponent $comOn){}
    public function remove(IComponent $comGone){}
    public function getChild($someInt){}
 
    /* Display tile */
    public function showPix()
    {
        echo "r1c1";
    }
}
?>

Each of the leaf classes is named after a column and row where the tile is to be placed. For example the leaf class to place an image in Row 2, Column 3 of the mosaic is named Leafr2c3. Likewise, the names of the PNG graphic files share the same naming conviction. So Leafr2c3 has the code to display the r2c3.png image file.

The Client

As an integral part of the Composite design pattern, the Client can be seen as the artist who composes the mosaic. He does this by selecting each tile for the rows and arranges them to get the desired picture. Because no string parameter is in the leaf constructors, each leaf added to a composition does not need a name. (In a sense, the title names have been embedded into the leaf names.) The $bigPictue property is the same name as used in the original Client example, except this time, it really will produce a “big picture.” It is the root composition made up of three row compositions that are made up of three leaf elements.


ERROR_REPORTING( E_ALL | E_STRICT );
ini_set("display_errors", 1);
function __autoload($class_name) 
{
    include $class_name . '.php';
}
class Client
{
    private $bigPicture;
 
    public function __construct()
    {
        $this->bigPicture = new Composite();
        $row1=new Composite();
        $row1->add(new Leafr1c1());
        $row1->add(new Leafr1c2());
        $row1->add(new Leafr1c3());
        $this->bigPicture->add($row1);
 
        $row2=new Composite();
        $row2->add(new Leafr2c1());
        $row2->add(new Leafr2c2());
        $row2->add(new Leafr2c3());
        $this->bigPicture->add($row2);
 
        $row3=new Composite();
        $row3->add(new Leafr3c1());
        $row3->add(new Leafr3c2());
        $row3->add(new Leafr3c3());
        $this->bigPicture->add($row3);
 
        //Create a compostion
        echo "";
        echo "";
        echo "";
        echo "

Leaders in Composition

"
; echo "
India
"
;   $this->bigPicture->showPix();   echo "
Mahatma Gandhi
"
; echo ""; } } $worker=new Client(); ?>

In this installment, the goal is to show that the Composite design pattern is more than a tree-like hierarchy-making pattern. It is the essence of composition and the Composite design pattern. The mosaic image is a metaphor for the pattern in that it is composed of several compositions and elements within those compositions.

Adding the Final Touches

With two unimplemented methods (remove() and getChild()), in Part III of this series, you will see how they can be used for added flexibility with the Composite design pattern. I’d like to look at the original Gang of Four idea of using the Composite pattern to create a drawing program. Until next time, I welcome any and all comments.

The Composite Design Pattern in PHP: Part I from Conceptual to Practical

compositionShow Me the Practical!

A defining characteristic of PHP programmers is their practicality. Ironically, because of their practical orientation, they sometimes overlook the practicality of the abstract and conceptual. Focusing too much on a single (albeit quite useful and practical) implementation is like focusing on a single pixel in a graphic image—you can only see the pixel and miss the larger picture. That’s because the focus is in the wrong place. If you want to see the whole picture (the whole pattern and its parts), the individual pixels are not very practical, even though they are the atomic matter in computer graphics. In other posts on this blog, I have stressed the importance of having a complete design pattern with all of the participants a given design pattern is designed to include and provided a look-up table to check the parts list of all of the core patterns the Gang of Four developed. So in selecting an example to launch a discussion of the Composite pattern, I wanted an example with all of its parts. You can download the files and play a sample using the following two buttons:
PlayDownload

However, too much of a love affair with the conceptual and abstract is equally problematic. If you cannot use a pattern to get something accomplished, why waste time with it? Ironically, design patterns were developed solely for practical purposes, but in order to accomplish those practical goals, they had to provide a set of patterns that would be useful for a wide range of certain recurring programming problems. With these concepts in mind, this post begins with a conceptual example to see how the pattern works and then follow it up with a simple more practical example.

Overview

First things first. The class diagram for the Composite design pattern is both very simple, but it hides a real beauty and subtle complexity. Figure 1 shows the basic pattern:

Figure 1: Composite Design Pattern class diagram

Figure 1: Composite Design Pattern class diagram

Before going too far with an example, even an abstract one, consider the simplicity and irony of the pattern. First of all, the Composite implementation of the Component interface looks fairly cut and dried. However, the Leaf participant also implements the interface, but it doesn’t implement all of the abstract methods. It only implements the operation(). So maybe the interface is an abstract class? It doesn’t matter in PHP. If all of the abstract methods of a class that inherits an abstract class are not implemented, you get the following error:

Fatal error: Class Leaf contains 1 abstract method and must therefore be declared abstract or implement the remaining methods

Since you can only declare an abstract method within an abstract class, you really have no choice but to implement it. Likewise with an interface all methods must be implemented; so with this first abstract example, I decided to use an interface instead of an abstract class.

Favoring Composition: A Tattoo for Your Spouse

One of the fundamental principles of design patterns is,

Favor object composition over class inheritance.

Figure 3: Tats for PHP Developers

Figure 3: Tats for PHP Developers

I tried to get my wife to get a tattoo with that piece of wisdom, but she balked at the idea. (I have no idea why; it’d be cool.) If any pattern adheres to that dictum, it’s the Composite pattern. The Composite participants are made up of Leaf primitives. So you can think of Composite implementations as compositions. The Leaf participants have no children. Think of the Leaf participants as parts that can be employed to create Composite participants.

For the longest time, that simple yet fundamental idea eluded me. In part, this was due to the Gang of Four’s intent statement that the pattern was to Compose objets into tree structures to represent part-whole hierarchies. I was too focused on the concept of hierarchy and not enough on compose to really appreciate the importance of the Composite design pattern.

So here, the first thing to do is to realize that the hierarchy is a form of composition. Imagine an automobile assembly plant where you have lots of parts, yet with those parts you can assemble different models of cars. You just have to use different selections of parts to compose the different models. The fact that the parts have a hierarchic arrangement is for efficiency; not the final product itself. Figure two shows what we hope to create in this initial implementation:

Figure 2: Different Compositions from Leaf Selections

Figure 2: Different Compositions from Leaf Selections


Continue reading ‘The Composite Design Pattern in PHP: Part I from Conceptual to Practical’

Check All of the Participants: Design Pattern Parts List

legtablecatpicStill Missing Parts

Several years ago I wrote a post, Why Are PHP Design Patterms Missing Pieces? I looked at a lot of PHP design patterns and found that several have major missing parts. In one of the earliest list of PHP design patterns on an IBM-sponsored site from 2006, for example, the Factory pattern is described and it has an example, but the Simple Factory (which was the actual pattern shown) is not the same as the Factory Method pattern that includes four participants: Product, Creator, Concrete Product and Concrete Creator. Generally, the “Creator” is used interchangeably with “Factory” and there seemed to be a lot of developers who make Simple Factory designs, but they only get an ‘honorable mention’ from the Freemans as a design pattern. (The Freemans refer to the Simple Factory as a programming idiom.)

PHP Gets No Respect!

I hate it when C# snobs or Java divas stick up their noses at PHP developers, but when you look at the design patterns attributed to The Gang of Four, these other languages have fully developed examples (the Freemans’ Head First Design Patterns, being first among them). However, we don’t have so many, and if you look at the examples online, you’ll see that many are missing parts. Rather than rage at the storm and what makes us PHP developers look like a collection of befuddled hackers, I’ve created a new column for the “Variation and Intent” table that lists all of the Participants—it’s sort of a Parts List for design patterns. Click the Play button to see the new table:
Play
The italicized participants are abstract classes or interfaces. Often the examples in PHP may be perfectly good examples of OOP programming, but they’re not design patterns nor do they offer the advantages of design patterns. Others, like the table pictured with a missing leg, can set up the developer for problems somewhere in the program. So, if you have a design pattern with a missing part, ask yourself,

What could possibly go wrong?

Don’t Forget the Client!

The Client object is listed as a direct or implied participant in most of the design patterns. It is further mentioned in the collaboration of several others. In the original Gang of Four tome, you will see several class diagrams with the Client “ghosted” (light gray) indicating an implied role. However, in nearly half of the patterns, the Client is an integral part of the pattern. You’d be surprised how many developers leave them out or (worse) refer to them as “main” (a leftover from C++). In any event, I’ve included all of the Client participants, including those implied. Also, you will see where the Client is mentioned in collaboration with the main participants.

Use the Participant Column as a Check List

The next time you go looking for a PHP design pattern to use, check to make sure it has all of its parts. The original collection released through the IBM site in 2006 fostered legions of incomplete PHP design patterns. These patterns have persisted over the years, and the only way to get back on the right track is to look at the original Gang of Four participants. Now that you have a parts list, you can check for yourself.