Archive for the 'Composite' Category

The Composite Design Pattern in PHP: Part IV Composite Drawing

killeAppA Composite Drawing Program

In the original Gang of Four Composite example, (pp. 163-173 of Design Patterns) they showed a drawing program. It was broken down into separate leaves for Line, Rectangle, and Text. I included those leaves and added a Circle leaf. On the first rendering, I used .svg files, but that turned out to be far more limited and awkward than I wanted. Since PHP is not known as a language for doing graphics like ActionScript and Python (or Java for that matter), I wanted to use it for a dynamic engine for taking advantage of the HTML5 svg tag. To my surprise (and delight) I found that everything worked quite well with all of the browsers. I still only used subset of the six basic shapes provided in the SVG 1.1 W3 release. Text is considered a separate object apart from the basic shapes of:

  • rectangle
  • circle
  • ellipse
  • line
  • polyline
  • polygon

Before going further, it will help to look at the code and the example of employing the Composite pattern with Scalable Vector Graphics(SVG). Also, your might want to look at Part I, Part II and Part III of the Composite Pattern series on this blog. Use the Play button to see the composite SVG creation and click the Download button to get a zip file with all the code for the application;
PlayDownload

SVG Leaves

This Composite example employs the structure and most of the code from the full pattern example from Part III of this series. The major changes are to the leaf elements and rendering in the Composite. However, not a lot has changed otherwise, and that is one of the essential features of design patterns: re-use. First, take a look at the rectangle leaf class:

< ?php
//Rectangle.php
class Rectangle extends IComponent
{
    private $xpos;
    private $ypos;
    private $wide;
    private $high;
    private $fill;
    private $stroke;
    private $strWidth;
 
    public function __construct($rx,$ry,$rw,$rh,$f,$sc,$sw)
    {
        $this->xpos=$rx;
        $this->ypos=$ry;
        $this->wide=$rw;
        $this->high=$rh;
        $this->fill=$f;
        $this->stroke=$sc;
        $this->strWidth=$sw;   
    }
 
    /* None of this batch of methods are used by shape or rectangle leaf */
    /* 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($int){}
    protected function getComposite() {}
 
    /* Draw Rectangle */
    public function draw()
    {  
        echo "<rect x='$this->xpos' y='$this->ypos' width='$this->wide' height='$this->high' fill='$this->fill' stroke='$this->stroke' stroke-width='$this->strWidth' />";
    }
}
?>
</rect>

It does not use most of the inherited abstract classes but implements them because the structure calls for it. The draw() method then sets up the SVG parameters for the rectangle shape. As you will see, the other leaf classes do the same thing in the continuing page:
Continue reading ‘The Composite Design Pattern in PHP: Part IV Composite Drawing’

Share

The Composite Design Pattern in PHP: Part III Getting Child Elements and Removing Composites and Leaves

removeGet the Children and Remove Them

If you haven’t looked at Part I and Part II of the Composite pattern series, you may want to do so first before looking at this post. As you saw in Parts I & II, the Composite pattern, while clearly working with a tree-like hierarchy is a great pattern that favors composition over inheritance, and as you work with this pattern, you’ll see why programming to the interface instead of programming to the implementation makes life easier for the programmer.

In this installment, I want to implement two key methods, getChild() and remove(). Going back to the beginning, again I’d like to use materials developed by former colleague and friend, Dr. Chandima Cumaranatunge. Also, I’m going to switch the main interface (IComponent) to an abstract class so that some of the methods can be implemented in the interface. Because both abstract classes and interfaces are both interfaces, the abstract class retains the name IComponent. To see all of the changes and the new implementations, first take a look at the outcome generated (click the Play button) and download the source code:
PlayDownload

Reference to Composites as Root Children

Up to this point, the Composite examples have worked perfectly well without implementing the getChild() method. All access to the composites and leaves has been handled by the operation() method. Why bother? First of all, the Client can directly access any single node. The child the program is “getting” is either a composite or a leaf, and there will be no need to iterate through the entire root component to find a single node. Secondly, and more importantly, the Client can create new nodes without creating new variables. When a node is removed, this insures good garbage collection. (Garbage collection, in this context, refers to regaining unused resources and memory used by the nodes that have been removed.) It makes for cleaner and faster operations.

Since the getChild() is part of the interface, first take a look at the abstract class. Then, we’ll look at the implementation in the Composite class.

< ?php
abstract class IComponent
{
    protected $parentNode;
 
    abstract function operation();
    abstract function add(IComponent $comOn);
    abstract function remove(IComponent $comGone);
    abstract function getChild($int);
    protected abstract function getComposite();
 
    protected function setParent(IComponent $compositeNode)
    {
        $this->parentNode=$compositeNode;
    }
 
    public function getParent()
    {
        return $this->parentNode;
    }
 
    protected function removeParentRef()
    {
        $this->parentNode=null;
    }
}
?>

As you can see, the getChild($int) method is still abstract with a single parameter. Were it possible in PHP, an int type-hint would be included in the parameter; so we’ll just have to make-do with the variable name, $int to assure that we remember to use an integer in the parameter. However, the method’s implementation is pretty straightforward:

public function getChild($int)
{
   if(($int > 0) && ($int < = count($this->aChildren)))
    {
        return $this->aChildren[$int-1];
     }
     else
     {
         return null;
     }   
}

The method checks the value of the integer to make sure it’s greater than zero and greater than or equal to the length of the array (aChildren) and then returns the requested object as an element of the array. Otherwise, it returns a null value.

The value of the method becomes apparent in the Client reference, as the following snippet from the Client shows:

...
$this->rootCompos=new Composite("Root");       
$this->rootCompos->add(new Composite("-Composite 1"));
$this->rootCompos->getChild(1)->add(new Leaf("--C1:leaf 1"));
...

On the third line of the snippet, the leaf is added to the first child (a Composite instance) instead of to a variable holding the reference to the first child. As you will see, this approach requires no new variable for the composite name.

Safe Removal

In an earlier version of a Composite design I had made, I used something like the following to implement the remove() method:

function remove(IComponent $node)
{
    $nodeNow = array_search($node, $this->aChildren);
    unset($this->aChildren[$nodeNow]);
}

That works fine, but to my surprise, I found that others considered it “unsafe.” Specifically, the Freemens (Head First Design Patterns p367) noted that a Client might inadvertently try to add a composite element to a leaf node.
Continue reading ‘The Composite Design Pattern in PHP: Part III Getting Child Elements and Removing Composites and Leaves’

Share

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.

<?php
//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.

<?php
//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.

<?php
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 "<img src='images/r1c1.png' alt='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.

<?php
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 "<!doctype html><html><head>";
        echo "<link rel='stylesheet' href='india.css'>";
        echo "<meta charset='UTF-8'></head><body>";
        echo "<h1>Leaders in Composition</h1>";
        echo "<header>India</header>";
 
        $this->bigPicture->showPix();
 
        echo "<figcaption>Mahatma Gandhi</figcaption>";
        echo "</body></html>";
    }
}
$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.

Share

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’

Share