Monthly Archive for October, 2013

PHP Builder Design Pattern Part I: One Process, Many Representations

builderCover250Let’s Build Something!

A lot of the work PHP developers do involves creating the same thing with variations. For example, you may create a Web site with different organizations for desktop displays, tablet screens and mobile views. However, you want the content the same, and while set up differently, you want to have a navigation system, headers, links and all the rest that goes into a Web site. The same is true for working with MySQL, and forms of different kinds. You can create fairly complex objects, but the representations (e.g., desktop, smartphone) are different. The Builder Design pattern is a creational pattern that lets you separate the construction of complex objects from their representations so that the same construction process can create different representations. Before going further, take a look at two different results in the PlayA and PlayB buttons and download the source code:
PlayAPlayBDownload

The Simple Builder

This first example looks at creating a simple Builder pattern with all of the parts laid out and pretty spread out. Two Client objects call two different concrete builders, and while that would have been pretty easy to do with a single Client the purpose of this first example is to clearly show each of the parts. In Part II, you’ll see a more streamlined and functional version of a Builder, but for now, it’s important to see how this thing works. Before going further, take a look at the Builder class diagram in Figure 1:

Figure 1: Builder Class Diagram (with Client added)

Figure 1: Builder Class Diagram (with Client added)

As noted in Figure 1, I added the Client, and according to the Gang of Four,

The client creates the Director object and configures it with the desired Builder object.

So, the Client, while not a participant in the pattern, is clearly a key collaborator. However, I put the Client code at the end of this post because its role must be understood in the context of the Builder’s key participants.

The Builder Interface

It’s difficult to know where to begin in describing the Builder pattern; but starting with the Interface helps show the main building blocks.

< ?php
//IBuilder.php
interface IBuilder
{
        public function mainHead();
        public function subHead();
        public function buildNavH();
        public function buildNavV();
        public function buildGraphic();
        public function buildVideo();
        public function buildBodyText();
}
?>

In looking at the IBuilder interface, you can see what might be the parts of a Web page. Keeping in mind that this example is a simple one, the example is a Web page “wire framer.” That is, it creates a graphic outline of what the page will look like using SVG graphics generated dynamically in the program.
Continue reading ‘PHP Builder Design Pattern Part I: One Process, Many Representations’

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>

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’

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’