Friday, January 29, 2010

Practical Php Patterns: Facade

This post is part of the Practical Php Pattern series.

The structural pattern of today is the Facade one.
A Facade is a class that provides a unified interface to a subsystem, totally abstracting away the concrete classes which compose it. The Client is thus decoupled from the internals of the Facade's module.
This pattern is usually implemented to reduce coupling between subsystems and towards vendor code; libraries often provide a Facade to hide their internals and being able to change them in subsequent releases (e.g. the Doctrine static class in Doctrine 1.x is a Facade, and the EntityManager one is its equivalent in Doctrine 2; the Facade remained unchanged in every release of the same branch.)

There are some important glitches you have to avoid while implementing a Facade:
  • it should not be a Singleton or a static class; otherwise the global state of the subsystem will be hidden under the Facade, effectively preventing isolation of tests that involve. Imagine test against a database schema you cannot ever reset. Doctrine 1 was fundamentally flawed from this point of view.
  • The Facade should only return and accept interfaces or value objects in its method signatures, so that there are no transitive dependencies. If the Facade gives away references to the internal collaborators of its module, it won't achieve its decoupling goal.
The job that the code sample accomplishes is outrageously simple. I know some readers would prefer a real world situation, but often the domain details obscurate the intent of the described pattern. That's why programming languages manuals start with Hello World programs and not with real world situations which bring in thousands of lines of code.
<?php
// Various classes we want to shield the Client from.
class Adder
{
    public function add($a, $b)
    {
        return $a + $b;
    }
}

class Subtractor
{
    public function subtract($a, $b)
    {
        return $a - $b;
    }
}

class Multiplier
{
    public function multiply($a, $b)
    {
        return $a * $b;
    }
}

class Divider
{
    public function divide($a, $b)
    {
        if ($b == 0) {
            throw new Exception('Division by zero.');
        }
        return $a / $b;
    }
}

// Client code
$adder = new Adder();
echo '254 + 113 = ', $adder->add(254, 113), "\n";
$divider = new Divider();
echo '256 / 8 = ', $divider->divide(256, 8), "\n";
Application of a Facade class to the previously presented code:
<?php
include_once 'BeforeFacade.php';

class CalculatorFacade
{
    public function __construct(Adder $adder,
                                Subtractor $subtractor,
                                Multiplier $multiplier,
                                Divider $divider)
    {
        $this->_adder = $adder;
        $this->_subtractor = $subtractor;
        $this->_multiplier = $multiplier;
        $this->_divider = $divider;
    }

    public function calculate($expression)
    {
        list ($a, $operator, $b) = explode(' ', $expression);
        // eliminating switch constructs is not in the intent of this pattern
        switch ($operator) {
            case '+':
                return $this->_adder->add($a, $b);
                break;
            case '-':
                return $this->_subtractor->subtract($a, $b);
                break;
            case '*':
                return $this->_multiplier->multiply($a, $b);
                break;
            case '/':
                return $this->_divider->divide($a, $b);
                break;
        }
    }
}

class CalculatorFactory
{
    public function getCalculator()
    {
        return new CalculatorFacade(new Adder(), new Subtractor(), new Multiplier(), new Divider());
    }
}

// Client code
$calculatorFactory = new CalculatorFactory;
$calculator = $calculatorFactory->getCalculator();
echo '254 + 113 = ', $calculator->calculate('254 + 113'), "\n";
echo '256 / 8 = ', $calculator->calculate('256 / 8'), "\n";
In the example, the library vendor or the component's owner is now free to change the internal concrete classes. Moreover, he can still change signatures and move methods between classes, a feature that even by using Abstract Factories to return Adder and its sibling classes cannot be achieved. Only external interfaces are published, while the contracts between internal classes are not refererred to in any way, stimulating internal refactoring and shifting of responsibilities between classes. For instance, we can easily merge or extract classes and introduce collaborators without the Client code being affected.
Facade is one of the most powerful decoupling patterns because it hides every unnecessary assumption beyond a heavy curtain, thus preventing change in a software module, which will certainly happen, from spreading in the whole application.

Thursday, January 28, 2010

Writing a Facebook application

Facebook is the largest social network in the world (300 million users) and it is surely a showcase for web applications. You can easily write a self-hosted application that interacts with the Facebook Api, obtaining access to the user details and relieving from registration and preferences management issues.
There are two ways to code such an application: FBML, a markup language created by Facebook, versus creating an iframe application. In the latter case, which is the most interesting, the application will run on your hosting server and will be embedded in a Facebook page. This choice gives you more freedom in data processing and technology since the application will be a real web application, with the addition of an interface to Facebook data.

The starting page for creating a web application is http://developers.facebook.com/get_started.php; there is a list of steps to complete such as:
  • downloading the official php library and placing it wherever you want, for inclusion in php scripts; of course there are other libraries to take advantage of the same Api, written in other programming languages, but php is the most comfortable choice for the majority of this blog's audience.
  • Register the application in the Developers application.
  • insert the callback (url of your server) and canvas (official url of the application) urls; canvas is the generic term for the Facebook page where your application resides.
After a successful setup, the Developers application will very friendly provide you some sample code to list the first 25 friends of an user that visits the application, with your application keys already inserted in the bootstrap code.

To try out Facebook's environment, I decided to write a throw away php application that automatically declines events whenever they contain a list of spamming keywords chosen by the user. The keywords are stored in a mysql database on its own server.
Currently NoSpam runs on my home server because I could not find a free php hosting service which has Pdo_Mysql and stream_context_wrapper() enabled at the same time. (Do you know any?)

XFBML
A standalone hosted app is very easy to create because there is no difference with the web application that we all know. But it's a matter of fact that it will need to create Facebook widgets: for instance requiring authorization for doing almost anything interesting is commonly achieved with a Facebook javascript popup that prompts the user for extended permissions. In my case, I had to require authorization to rsvp to events in the user's place.
The solution for taking advantage of precooked Facebook widgets resides in XFBML, an Xhtml namespace that allows you to embed Fbml tags in your html and having them parsed when the iframe is loaded, much like Dojo declarative model.
A guide for setting up XFBML can be found on the Facebook developers' wiki: http://wiki.developers.facebook.com/index.php/XFBML
Everyone says that xhtml sucks, but it is a standard for this really useful feature. Once XFBML is set up, creating a button that asks for extended permissions is as easy as:
<fb:prompt-permission perms="rsvp_event">Allow NoSpam to respond to your events invitation.</fb:prompt-permission>
Php
The role of Php in this adventure has been fantastic: it scaled down just enough to allow me building a throw-away application, since my goal was learning how the facebook infrastructure works. I wrote only 1 class, and all the setup was in my index.php (which is only ~100 hundred lines of code long).
I am trying different hosting services (which usually are the driving force of php, but they have always interesting features and extensions disabled or not compiled at all), and all it takes to deploy the NoSpam app, to judge if it can work in an hosting environment, is uploading the files and create the mysql database. No compiling, no packaging, no dependencies resolution, no libraries of any kind but the Facebook official one. Php can create monsters sometimes, but it's certainly the path of least resistance between a web developer and a working prototype.

Note that I have not TDDed this application since I plan to throw it away. When you're working in a new environment, the best thing to learn how it works is to dive in the code.

Monday, January 25, 2010

Practical Php Patterns: Decorator

This post is part of the Practical Php Pattern series.

Today we will explore the Decorator pattern, an alternative to subclassing which favors object composition over class inheritance.
A common issue of subclassing is its rigidity: when different subclasses provide different features, it's hard to combine them into a unique object.
A classic example consists in considering a Ball class and two BouncingBall and ColoredBall subclasses. What should I instantiate if I want a ColoredBouncingBall? There are different solutions that fall in the subclassing realm:
  • one more subclass is created; often multiple inheritance is not allowed and thus some code from BouncingBall or ColoredBall would be duplicated.
  • If the desired ball traits are three or more, for instance because a RollingBall class exists, there would be a proliferation of subclasses: ColoredBouncingBall, ColoredRollingBall, BouncingRollingBall and ColoredBouncingRollingBall. If you add a business requirement (the client wants rolling balls) and the codebase explodes, this is a sign that something is wrong in the design: when two different balls are requested, we should take the first bullet and refactor into a Decorator pattern, where every other trait will require only one additional class instead of doubling the number of concrete classes.
  • We can also prepare a God class that puts together the different Colored and Bouncing behaviors, but remember that a class should have only one responsibility. Why adding traits that sometimes will never be used to an object? This solution forces all Balls to be an instance of BouncingColoredRollingBorderedFlashingBall.
The Decorator pattern is a standard response to a big subclassing tree. It can often be viewed as a particular Composite pattern, whose Uml diagram is very similar, when there is only one Component and Composites (ConcreteDecorators) adds functionalities instead of aggregating various objects. In fact, they compose only one instance of Component, instead of subclassing it.
Their job is to delegate all the methods of the Component interface to the wrapped Component instance, and to decorate some of them with additional behavior. Since the wrapping and delegation code is common to all the ConcreteDecorators of the same Component, it is usually shared in a base class.
Since Decorators work on a Component and not on ConcreteComponents, they can compose other Decorators, showing their affinity to the Composite pattern. In the diagram, ConcreteDecorators (which are not shown) would be subclasses of Decorator, which keep the inheritance tree at only one level of depth.
Since Decorators conform to Component, the Client does not notice if a ConcreteComponent is substituted with a Decorator composing it, or with a Decorator composing a Decorator composing it.

The code sample is provided in a Before & After form, referring to the application of the pattern to a design problem. This new form is a useful suggestion from an anonymous reader.
The pattern implementation is similar to Zend Framework's Zend_Form component's decorators, but those kind of decorators are implementations of a "renderer" interface Zend_Form_Decorator and not of the entire element interface.
Before
<?php
/**
 * Represents a <input type="text" /> html element.
 * It can be created programmatically and then printed.
 */
class InputText
{
    protected $_name;

    public function __construct($name)
    {
        $this->_name = $name;
    }

    public function getName()
    {
        return $this->_name;
    }

    public function __toString()
    {
        return "<input type=\"text\" id=\"{$this->_name}\" name=\"{$this->_name}\" />\n";
    }
}

/**
 * Adds a custom <label> element alongside the <input> one.
 */
class LabelledInputText extends InputText
{
    protected $_label;

    public function setLabel($label)
    {
        $this->_label = $label;
    }

    public function __toString()
    {
        return "<label for=\"{$this->_name}\">{$this->_label}</label>\n"
             . parent::__toString();
    }
}

/**
 * Adds a <span> containing an error message after the <input> element.
 */
class ErrorInputText extends InputText
{
    protected $_error;

    public function setError($message)
    {
        $this->_error = $message;
    }

    public function __toString()
    {
        return parent::__toString()
             . "<span>{$this->_error}</span>\n";
    }
}

$input = new LabelledInputText('nickname');
$input->setLabel('Nick:');
echo $input, "\n";

$input = new ErrorInputText('nickname');
$input->setError('You must enter a unique nickname');
echo $input;

// but how can we obtain a LabelledErrorInputText, which has both the <label>
// and <span> elements? The subclassing-based design has clear limitations.
After
<?php
/**
 * The smallest cohesive interface we can think of for this type
 * of Decorator. This is the Component interface.
 */
interface HtmlElement
{
    /**
     * @return string    html code
     */
    public function __toString();

    /**
     * @return string    the name of the POST request key for this element,
     *                   aka the "name" attribute.
     */
    public function getName();
}

/**
 * Represents a <input type="text" /> html element.
 * It can be created programmatically and then printed.
 * This is the only ConcreteComponent.
 */
class InputText implements HtmlElement
{
    protected $_name;

    public function __construct($name)
    {
        $this->_name = $name;
    }

    public function getName()
    {
        return $this->_name;
    }

    public function __toString()
    {
        return "<input type=\"text\" id=\"{$this->_name}\" name=\"{$this->_name}\" />\n";
    }
}

/**
 * Very simple base class to share the wrapping code between Decorators.
 * This is the Decorator participant.
 */
abstract class HtmlDecorator implements HtmlElement
{
    protected $_element;

    public function __construct(HtmlElement $input)
    {
        $this->_element = $input;
    }

    /**
     * All operations are delegated by default, not changing anything
     * of the original behavior.
     * ConcreteDecorators will override the methods they are interested in.
     */
    public function getName()
    {
        return $this->_element->getName();
    }

    public function __toString()
    {
        return $this->_element->__toString();
    }
}

/**
 * Adds a custom <label> element alongside the <input> one.
 * Example of ConcreteDecorator.
 */
class LabelDecorator extends HtmlDecorator
{
    protected $_label;

    public function setLabel($label)
    {
        $this->_label = $label;
    }

    public function __toString()
    {
        $name = $this->getName();
        return "<label for=\"{$name}\">{$this->_label}</label>\n"
             . $this->_element->__toString();
    }
}

/**
 * Adds a <span> containing an error message after the <input> element.
 * Example of ConcreteDecorator.
 */
class ErrorDecorator extends HtmlDecorator
{
    protected $_error;

    public function setError($message)
    {
        $this->_error = $message;
    }

    public function __toString()
    {
        return $this->_element->__toString()
             . "<span>{$this->_error}</span>\n";
    }
}

$input = new InputText('nickname');
$labelled = new LabelDecorator($input);
$labelled->setLabel('Nick:');
echo $labelled, "\n";

$input = new InputText('nickname');
$error = new ErrorDecorator($input);
$error->setError('You must enter a unique nickname');
echo $error, "\n";

// how can we obtain a LabelledErrorInputText, which has both the <label>
// and <span> elements?
$input = new InputText('nickname');
$labelled = new LabelDecorator($input);
$labelled->setLabel('Nick:');
$error = new ErrorDecorator($labelled); // a Decorator wrapping another one
$error->setError('You must enter a unique nickname');
echo $error;
The resulting architecture of a Decorator pattern is a graph of the mandatory number of cohesive classes and small objects, which is highly preferable to a high number of classes and God objects. The final behavior is not obtained by choosing something to subclass but by instantiating different Decorators and linking them in a chain of objects, while maintaining the original Component abstraction all the time.

I hope you liked the "before and after the cure" style of this article. It may become the norm for the next posts of this series.

Friday, January 22, 2010

Teachers and the value of formal education

Question: is it clever to drive for half an hour and drive back another half hour to listen to a 90 minutes lecture?
If the teacher is worth it, yes. At Politecnico di Milano I found out that very often the professors are not in their position because of some random event. And what is true for school and university professors is usually true for other kinds of teachers, like consultants and coaches.
When I give advice on php applications, I do my best to distill knowledge from my previous experience, like a good teacher would do. The focus in every technical subject is not on giving fish, but in teaching how to fish.

You probably want to improve yourself and your career if you're reading here. So, what a teacher or a mentor gives you in order to become better?
  • interest for the discipline: maybe the most important  job of a professor is stimulating interest and passion about his subject. I am glad that many teachers I encountered during my education left me with a desire to deepen my understanding of computer science. Many did not - maybe I would be a little more knowledgeable on history if I did not become fascinated by it only half the way in high school, because of the way my teacher conducted lessons. The only thing I remember before the year 1000 is that the Roman Empire was formerly a republic.
  • Insights which we could take years to arrive to: the fact that, as engineers, we focus on the technology-independent algorithms is still one of the best lesson I have learnt during this semester. Or let's talk about the importance of conservation laws...
  • Solution to a question in a few seconds as an authoritative source. However, we should not abuse a teacher's time: even the best professor may be wrong or outdated sometimes, and other students have the same right for teacher's time as us.
  • Goals which are adequate to the industry standard. If you are very interested in the discipline, maybe you'll want to expand those goals.
  • And yes, a degree which should be useful when you apply for a job.
And what you invest in a teacher?
  • money: subscription to the high school or university, or fee if he's a private teacher, Agile coach, etc. In Italy nearly all the universities are public and I am in range to go everyday to the best  technical university of the country (this may only be luck); this means that I will graduate debt-free and I am scared by seeing people in US taking a 50,000 or 100,000 dollars loan to cover education expenses. Wouldn't you think that Harvard isn't lucrating on subscriptions? At least MIT created Open Course Ware.
  • Time to schedule and show up at encounters such as lessons and exercises sessions. If you are very familiar with a subject you may skip lessons altogether to save time, but beware of spending more time in catching up with the lessons than the one you saved by skipping them.
  • Will to work hard instead of sleeping all morning.
Courses in database systems, computer science, software engineering... are probably the smartest way to become a qualified, all-round software developer. Today I am going to the last semester lesson at 14:15 CET.

    Wednesday, January 20, 2010

    Practical Php Patterns: Composite

    This post is part of the Practical Php Pattern series.

    One of the most important structural patterns is the Composite one: its goal is managing a hierarchy of objects where both leaf objects and composition of other objects conform to a common interface. This hierarchy is usually constituted by part-whole relationships (often composition in the strict sense or aggregation), and it can be viewed as a tree.
    The power of the Composite pattern resides in a Client which refers only to a Component interface, the common abstraction between all kinds of tree elements, and it is  oblivious to changes in the underlying structure. The Client is not even aware of the hierarchical structure existence and it is passed a reference to the tree head.
    Meanwhile, the Composite responsibility is to build on its Component children's operations, and propagate their calls towards the bottom of the hierarchical graph until they reach Leafs.

    Participants:
    • Client: sends message to the head Component.
    • Component: declares the interface that various parts of the graph should respect.
    • Leaf: concrete class that has no children.
    • Composite: concrete class that composes other Components (no pun intended).
    The code sample shows a Composite pattern in action to duplicate a small subset of Javascript's Document Object Model.
    <?php
    /**
     * Component interface.
     * The Client depends only on this abstraction, whatever graph is built using
     * the specializations.
     */
    interface HtmlElement
    {
        /**
         * @return string   representation
         */
        public function __toString();
    }
    
    /**
     * Leaf sample implementation.
     * Represents an <h1> element.
     */
    class H1 implements HtmlElement
    {
        private $_text;
    
        public function __construct($text)
        {
            $this->_text = $text;
        }
    
        public function __toString()
        {
            return "<h1>{$this->_text}</h1>";
        }
    }
    
    /**
     * Leaf sample implementation.
     * Represents a <p> element.
     */
    class P implements HtmlElement
    {
        private $_text;
    
        public function __construct($text)
        {
            $this->_text = $text;
        }
    
        public function __toString()
        {
            return "<p>{$this->_text}</p>";
        }
    }
    
    /**
     * A Composite implementation, which accepts as children generic Components.
     * These children may be H1, P or even other Divs.
     */
    class Div implements HtmlElement
    {
        private $_children = array();
    
        public function addChild(HtmlElement $element)
        {
            $this->_children[] = $element;
        }
    
        public function __toString()
        {
            $html = "<div>\n";
            foreach ($this->_children as $child) {
                $childRepresentation = (string) $child;
                $childRepresentation = str_replace("\n", "\n    ", $childRepresentation);
                $html .= '    ' . $childRepresentation . "\n";
            }
            $html .= "</div>";
            return $html;
        }
    }
    
    // Client code
    $div = new Div();
    $div->addChild(new H1('Title'));
    $div->addChild(new P('Lorem ipsum...'));
    $sub = new Div();
    $sub->addChild(new P('Dolor sit amet...'));
    $div->addChild($sub);
    echo $div, "\n";
    Some notes on the implementation:
    • evaluate if maintaining parent references in Component specializations would be a waste of time. This addition prevents sharing of objects as children of different Composites and makes the mutual reference management more complex.
    • often also the remove() operation is not even required in php implementations, because of the transient nature of object graphs. It is rare to modify a tree unless if its objects are entities; service trees such as Chains of responsibility are built via configuration at the startup.
    • the only operation which is really mandatory, besides the ones present in the Component interface, is a way to specify the children, via an add() method or the constructor.
    • a Builder can encapsulate the mechanics of the construction process of the object tree.

    Tuesday, January 19, 2010

    Relationships between objects

    This article implements the beginner pattern, but it can also be useful to recap the terms we use lightheartedly in discussions about object-oriented programming.

    In the definitions, we will talk about a relationship between a Source and Target objects, or equivalently between a Source and Target class. In general, there are some orthogonal properties that can be assumed by nearly any relationship:
    • multiplicity: a relationship may link to one target or to N targets
    • directionality: a relationship may be unidirectional (Target has no idea it exists) or bidirectional (Target has an inverse relationship towards Source).
    Is-a relationships
    In this kind of relationship, Source is an instance of Target and the operator instanceof, where available, returns true:
    $source = new Source(); 
    var_dump($source instanceof Target);
    There are two ways to obtain an is-a relationship.
    Inheritance (aka subclassing) is a unidirectional, many-to-one relationship which is commonly declared with the keyword extends in php and other programming languages. Source inherits all the protected and private methods and properties of its unique Target.
    Implementation is a relationship towards a Target interface where the Source class declares (with the implements keyword) that its public methods conform to Target's signatures definition. A Source can implement multiple Targets, but it does not inherit concrete code from any of them.
    Subclassing is often abused to exploit the methods inheritance. Moreover, it is a static property because you cannot change the Target superclass at runtime. Substituting it with an implementation often improves the situation because Source can then have multiple parent classes (but you must be careful that a real is-a relationship is still present).

    Has-a relationships
    An has-a relationship is established when a Source object maintains a field reference to a Target object; this paradigm is applied to collaborators which are used throughout many methods of Source.
    Has-a relationships are called associations in Uml jargon, and there are two special forms of it.
    Aggregation is an association which implies a part-owner relationship. It is indicated with an empty diamond in Uml class diagrams.
    Composition is a particular aggregation in which the parts (which are the Source objects) cannot be shared with other Targets. This difference is reflected by a black diamond. Both specializations have a multiplicity of one.
    There may be associations which are neither aggregations nor compositions, since they are references to an external service for example. The term composition is often used for antonomasia to indicate every kind of association, particularly in the catch phrase Favor composition over inheritance.
    If done right (without an hardcoded new operator or creation method), an association is not a static relationship because you can decide at runtime what the pointer on Target or Source links to, as long as the destination object is-a implementation or subclass of the original one.

    Dependencies
    A dependency is established when Source knows Target someway and if we delete Target, the Source class cannot work correctly anymore. Maybe it does not compile, maybe it generates errors or exceptions when certain methods are called. Maybe Source creates Target (if it is a Factory), but the common case is an object passed as a method parameter.
    Another cases we may encounter is a dependency towards a Singleton. This is an awkward case because the dependency is hidden and the Api does not show it clearly. The same goes for collaborators created in the constructor or methods instead of being asked for.

    It can be said that the has-a and is-a relationships are stronger cases of dependency, since an hypothetical deletion of the Target breaks Source in both cases.
    Here's the catch: most of these dependencies cannot be avoided; what we can do is keeping abstractions as Target of dependencies, such as interfaces and base classes. The less code classes depends on, the more decoupled and versatile is the design: interfaces have no code at all (except for method signatures) and are the best thing to depend on in object-oriented programming. They are the ideal point of conjunction of different modules and object graphs.
    Abstract and base classes have little code too, but they can grow quickly and you can inherit only from one of them, while not being able to change the Target class easily.

    I hope this formal definitions of relationships will help you better comprehend the articles in the Design Pattern series, especially the ones to come.

    Monday, January 18, 2010

    Practical Php Patterns: Bridge

    This post is part of the Practical Php Pattern series.

    Today we will explore the Bridge pattern, whose intent is separating an abstraction from its implementation to improve decoupling and allowing them both to change independently.
    Commonly an abstraction is thought as an interface implemented by several concrete classes; but there are other means to obtain the same result.
    The Bridge pattern is one of these ways - it is similar to the Adapter pattern, but its underlying motivation is different: an Adapter makes two unrelated, existing classes work together, when the two participants were not thought to be aware of each other during design, or they must not be coupled as part of different modules. A Bridge is a structure that separates concerns and which is chosen at the design level, before the creation of the participants classes.
    The Abstraction that a Bridge shows to the Client is a class that composes an Implementor interface. Two trees may develop: the abstraction hierarchy and the implementation one. Without this differentiation, the two hierarchies would be merged and the result would be a growing number of classes needed to cover the combinations of RefinedAbstractions and ConcreteImplementors.
    This pattern is a powerful example of favoring composition over inheritance, one of the motifs of the GoF design patterns book. The link between abstraction and implementation consists in an has-a relationship whose target is set at runtime, and that can be extended without the end user of the Abstraction noticing.

    Participants:
    • Abstraction: the ultimate interface that the Client sees.
    • Implementor: the segregated interface created for providers of an actual implementation.
    • RefinedAbstraction: extension of the Abstraction functionalities.
    • ConcreteImplementor: realization of Implementor.
    The code sample shows a Bridge implementation for a Website data structure used to store a search engine's data.
    <?php
    /**
     * SECTION 1: Implementor hierarchy.
     * Implementor: a small bean that provides basic methods for accessing
     * data on a single Website.
     */
    interface WebsiteImplementor
    {
        /**
         * @param string $address
         * @return boolean
         */
        public function containsLinkTo($address);
    
        /**
         * @return string
         */
        public function getAddress();
    }
    
    /**
     * ConcreteImplementor.
     * Another implementation could be CrawlerWebsiteImplementor which scans pages
     * on a as-needed basis to find links.
     */
    class IndexedWebsiteImplementor implements WebsiteImplementor
    {
        private $_address;
        private $_links;
    
        public function __construct($address, array $linked)
        {
            $this->_address = $address;
            $this->_links = $linked;
        }
    
        public function getAddress()
        {
            return $this->_address;
        }
    
        public function containsLinkTo($address)
        {
            return in_array($address, $this->_links);
        }
    }
    
    /**
     * SECTION 2: Abstraction hierarchy.
     * Abstraction.
     * Additional operation can be concrete methods on an abstract class,
     * but a Bridge frees the Implementors from extending a single base class.
     * For example, different Abstractions can use the same Implementor
     * objects and classes if necessary, while if Implementor extends something
     * it remains tied to the base class.
     */
    class Website
    {
        private $_imp;
    
        public function __construct(WebsiteImplementor $imp)
        {
            $this->_imp = $imp;
        }
    
        public function getAddress()
        {
            return $this->_imp->getAddress();
        }
    
        public function containsLinkTo($anotherWebsite)
        {
            if ($anotherWebsite instanceof Website) {
                $anotherWebsite = $anotherWebsite->getAddress();
            }
            return $this->_imp->containsLinkTo($anotherWebsite);
        }
    
        public function containsLinks(array $addresses)
        {
            $result = true;
            foreach ($addresses as $a) {
                if (!$this->containsLinkTo($a)) {
                    $result = false;
                }
            }
            return $result;
        }
    }
    
    /**
     * RefinedAbstraction for presentation purposes.
     * It would not be possible to create a PresentationWebsite which presents
     * the same interface to the Client *for every type of WebsiteImplementor*
     * if we were using an abstract class (that ConcreteImplementors extend)
     * for the Abstraction operations.
     * In that case, we would have been forced to create PresentationIndexedWebsite,
     * PresentationCrawlerWebsite, ...
     */
    class PresentationWebsite extends Website
    {
        public function getAddress()
        {
            $address = 'http://' . parent::getAddress();
            return "<a href=\"$address\">$address</a>";
        }
    }
    
    $links = array('www.google.com', 'www.twitter.com', 'www.youtube.com', 'giorgiosironi.blogspot.com');
    $websiteImp = new IndexedWebsiteImplementor('www.blogger.com', $links);
    $website = new Website($websiteImp);
    var_dump($website->containsLinks(array('www.google.com', 'www.youtube.com')));
    $presentationWebsite = new PresentationWebsite($websiteImp);
    echo $presentationWebsite->getAddress(), "\n";
    The Bridge pattern is typically used for:
    • avoiding an hardcoded relationship between an abstraction and its implementations. An abstract class which is extended by implementors becomes a class which composes an implementation of the missing functionalities.
    • Keeping the possibility of adding methods to an abstraction; adding methods to an interface breaks the implementations, while adding them to the Abstraction does not cause errors as long as they contain code. This possibility is widely used in libraries which have to deal with abstractions evolution and backward compatibility: some of them provide distinct Application Programming Interface for Clients and Service Programming Interface for ConcreteImplementors (more details).
    • Extending this choice further, the Implementor may really define only basic level operations, while the Abstraction centralizes higher-level methods that build on the functionalities of the Implementor. For instance if the Implementor defines the operation hasMethod(), the Abstraction can present also an hasMethods() one, preventing the code of the latter from duplication in all Implementors or Clients.
    • Segregating an interface when it grows to comprehend very similar methods, and its implementations duplicate code to satisfy the requirements accordingly. It might be the case to provide the higher-level operations on an Abstraction class which composes the Implementor interface (as presented in the code sample).

    Friday, January 15, 2010

    Practical Php Patterns: Adapter

    This post starts the Structural patterns part of the Practical Php Pattern series.

    Structural patterns are concerned with the structure of the object graph, and influence the hierarchy of subclassing, and where to introduce interfaces and associations.
    The first structural pattern we will touch is the Adapter pattern: an Adapter converts an already existent Adaptee class which presents a not usable (maybe implicit) interface to another Target interface, which other Clients components are ready to use.
    This pattern is often used to integrate different parts of an application, because it magically makes talk to each other classes which were strangers. You can consider also to modify the classes to improve their relationship, but only if you own them and no backward compatibility is required; the main problem resides in not introducing unnecessary coupling.



    In php, wrapping functions with a class can be considered an Adapter's implementation. Consider the Zend Framework codebase: it is full of adapters like Zend_Cache backends (which are wrappers) and authentication and database adapters.
    The full object-oriented case is also present: Zend_Paginator_Adapter_DbSelect is an Adapter for Zend_Paginator (Client) which swallows a Zend_Db_Select instance (Adaptee). Including a dependency on the Paginator would be a source of bloat and coupling for the Zend_Db component, so do not consider an Adapter only as a patch to make different libraries work together: its use is often mandtory even in the same application, to connect areas of different concerns.

    Participants
    • Client: makes use of an object which implements the Target interface.
    • Target: point of extension for the Client's module.
    • Adaptee: object of a different module or library.
    • Adapter: implementation of Target that forwards real work to the Adaptee, whilst totally hiding him.
    This is a code sample where the Adaptee is not a class, which is very common in php given the procedural approach of the majority of its extensions.
    <?php
    /**
     * The Target interface: a small Collection, since php lacks a native one.
     * The bigger the interface, the greater the hassle while writing Adapters.
     */
    interface Collection extends IteratorAggregate
    {
        public function add($element);
    
        /**
         * @return boolean
         */
        public function contains($element);
    
        public function remove($element);
    }
    
    /**
     * The Adaptee is not a class but an array.
     * This is the Adapter. Adapters for procedural structures are common in php,
     * much more than for classes. If it composed an object instead of an array
     * it would still be an implementation of the Adapter pattern.
     */
    class ArrayAdapter implements Collection
    {
        private $_array;
    
        public function __construct(array $array)
        {
            $this->_array = $array;
        }
    
        public function add($element)
        {
            $this->_array[] = $element;
        }
    
        /**
         * @return boolean
         */
        public function contains($element)
        {
            return in_array($element, $this->_array);
        }
    
        public function remove($element)
        {
            $index = array_search($element, $this->_array);
            if ($index !== false) {
                unset($this->_array[$index]);
            }
        }
    
        public function getIterator()
        {
            return new ArrayIterator($this->_array);
        }
    }
    
    /**
     * The Client. It would love to print an array, but it only
     * accepts Collections.
     */
    class Printer
    {
        public function printAndRemove(Collection $c)
        {
            foreach ($c as $index => $element) {
                $c->remove($element);
                printf("| %.6s => %.6s |", $index, $element);
            }
            echo "\n";
        }
    }
    
    // the Adaptee
    $array = array('foo', 'bar', 'baz');
    $adapter = new ArrayAdapter($array);
    $printer = new Printer();
    $printer->printAndRemove($adapter);
    var_dump($adapter->contains('foo'));
    In php, there is no private inheritance, so a class adapter (which subclasses the Adaptee) must not be considered as the resulting code would reflect a Decorator pattern instead; an object adapter is the mainstream solution, where the Adapter composes the Adaptee.
    There is also a choice between leaving abstract methods on the Client, that the Adapter will override so that it will be used directly, and a cleaner solution which favors object composition. The latter, which is presented in the example and in the diagram, consists in having the Adapter classes conform to a narrow and cohesive interface, which is passed to the Client on the stack or during construction. The Target should be kept short, since having twenty-six operations to implement is usually an inconvenience for the developer who has to write an Adapter.

    Thursday, January 14, 2010

    Practical Php Patterns: Creational patterns summary

    This post is part of the Practical Php Pattern series.

    It's useful to dedicate a post to summarize the various creational patterns we have studied so far.
    The goal of this recap is to outline differences between patterns to analyze each one's applicability. I am following the GoF book to simplify cross-references, but also enterprise patterns such as Unit Of Work and Data Mapper will be introduced later in the series.

    The most simple creational pattern is the Factory Method, which provides a simple hook method to redefine the instantiated class, but requires the programmer to subclass and override to modify the instantiation process. This is the shortest solution to quickly solve a creational issue.
    The other patterns are more powerful, but also require a little more code in their implementations:
    • Abstract Factory is a black box object that takes care of the creation and that can be specified as a collaborator. This is my primary, standard choice for solving the creation problem and php with its dynamic typing does not need an actual interface for factories, making this pattern even more favorable.
    • A Builder is a similar object, but it provides a richer interface to drive the creation process, still encapsulating the implementation details as much as possible. It is obvious that this pattern should be preferred when the need for customization of some object graph's traits is great.
    • A Prototype is a real instance of the class whose objects have to be created, that acts as a image to clone whenever it's required to do so. This pattern is mainly used to avoid hierarchies of factories and builders, and when many similar (but not identical) instances have to be handled in a Creator abstraction.
    Modern DI containers are essentially a set of configurable Abstract Factories; Guice for example implements a generics-powered Provider interface which acts as the AbstractFactory participant.
    Finally, the Singleton pattern should be used with caution. It often causes much more problems than the ones it solves.
    In the next posts, we will explore structural patterns, such as the Facade and Decorator ones.

    Wednesday, January 13, 2010

    Practical Php Patterns: Singleton

    This is the fifth post from the Practical Php Pattern series, which will touch the majority of the known design patterns, with a special look at their application in a php context and code samples.

    Today we will discuss the Singleton pattern, the most controversial creational pattern.
    A Singleton is a global point of access for a resource that must have only one instance in the whole application: database connections, http streams, and similar objects are the typical examples of such a class.
    This behavior is implemented trough a static method which returns a lazy-created instance, and by rendering the constructor private to avoid creation of an instance from outside the class code.
    The problems of a Singleton class are the same of its non object-oriented equivalent: a global variable. The Api of Clients of the Singleton lies, because they do not declare in any signature that they are taking advantage of the Singleton's capabilities; moreover, global mutable state is introduced and encapsulation is disregarded.


    There is a famous credit card example, which describes the usage of a CreditCard class. One day Misko Hevery was writing some tests in a system he does not know very well, to improve his knowledge of the codebase.
    He wrote this code:
    testCreditCardCharge() {
      CreditCard c =  new CreditCard(
        "1234 5678 9012 3456", 5, 2008);
      c.charge(100);
    }
    The test ran, and at the end of the month he got the bill and see he was out $100! The story is probably made up, but you get the point: if a Client references Singletons, you have no idea of what can happen when calling a method.
    The Api of CreditCard would have been honest if it was like:
    testCreditCardCharge() {
      CreditCard c =  new CreditCard(
        "1234 5678 9012 3456", 5, 2008);
      c.charge(100, creditCardProcessor);
    }
    Have you ever seen a CreditCard that can be used without a POS?

    In my opinion the classic Singleton pattern is adequate only if the static instance has no state, or it is an utility without side effects which you may want to substitute. The sample code reflects this weltanschauung.
    There are people that subclass Singletons, but if you feel the need to write a subclass it probably means you are already gone too far. Refactor the code to inject the Singleton as a collaborator of Client.

    PARTICIPANTS:
    • Singleton: class that manages to keep one and only one instance of itself.
    • Client: every class that references a Singleton.
    The code sample follows.
    <?php
    /**
     * The most harmless example of a Singleton I can think of is a Logger.
     * However, I feel that injecting the Logger or managing events with an
     * Observer pattern would be better here.
     * This Singleton infringes every rule of testability:
     * - constructor does real work
     * - destructor does other work
     * - constructor is private, you cannot instantiate it in tests
     * - instance is static, you cannot throw it away
     */
    class LoggerSingleton
    {
        private static $_instance;
        private $_fp;
        
        /**
         * We need only one instance, which will lock the file
         * from further editing.
         */
        private function __construct()
        {
            $this->_fp = fopen('log.txt', 'a');
        }
    
        public function __destruct()
        {
            fclose($this->_fp);
        }
    
        public function log($text)
        {
            $line = $text . "\n";
            fwrite($this->_fp, $line);
        }
    
        /**
         * An instance of this class is lazy created and returned.
         * No further instances are created if there is already one available.
         * This method is the standard way to create a Singleton.
         */
        public static function getInstance()
        {
            if (self::$_instance === null) {
                self::$_instance = new self();
            }
            return self::$_instance;
        }
    }
    
    /**
     * The Client receives a name and returns a welcome message, while
     * logging the operation.
     * *Little* side effect: it writes a file.
     */
    class Client
    {
        public function createWelcomeMessage($name)
        {
            LoggerSingleton::getInstance()->log("Greeted $name");
            return "Hello $name, have a nice day.\n";
        }
    }
    
    // isn't it strange that these two lines write a file on disk?
    $client = new Client();
    echo $client->createWelcomeMessage('Giorgio');
    The one instance myth is overrated, and there are other means to achieve the same behavior from a class. Test suites could have dozen of instances of "unique" services and connections (some of them as Fakes and Stubs); in fact, a proof of testability and good design consists in being able to run two applications in the same php script, Jvm or main method.
    The difference is that maintaining a unique instance is correct, but only within the boundaries of an application. If you control the creation process, your factories will never create more than one instance of a critical resource. Using a Singleton extends this uniqueness along all the execution environment and hides a crucial dependency under the carpet, effectively causing hassle to everyone trying to figure out what is going on, in debugging as in testing.

    Tuesday, January 12, 2010

    Practical Php Patterns: Prototype

    This is the fourth post from the Practical Php Pattern series, which will touch the majority of the known design patterns, with a special look at their application in a php context and code samples.

    Today we will discuss the Prototype pattern.
    The creation of objects in an application can be configured by metadata, for example by using Dependency Injection containers, or programmatically, in the case that it is accomplished by writing code.
    The most customizable option for programmatic creation is the Prototype pattern. This pattern consists in choosing an already existent object, with a clone() operation available, as the base for creating new objects of the same kind.

    Often the different objects that can be created by a Client are not instances of different ConcretePrototype classes, but different configurations of the same one; in this case the Prototype pattern may be used to provide all the different configurations to the Client, which needs to abstract away the object creation process.
    The Prototype pattern allows also:
    • management of available instances at runtime, performed simply by adding and removing operations on a collection of cloneable objects.
    • specification of new objects very similar to each other, by cloning an existing one and changing its properties using setters.
    • specification of new objects at runtime; a GoF example is about a circuit design system which lets the user insert already defined circuits as blocks of a new one. The circuits implement a clone() operation which clones all the components recursively.
    PARTICIPANTS:
    • Prototype: interface of the cloneable classes.
    • ConcretePrototype: implements the clone operations (the ones which are not already supported by the language).
    • Client: actually clones Prototype instances to use the clones as new objects.
    <?php
    /**
     * SECTION 1: a Widget interface and two different implementations.
     * Unlike in previous examples, where the Product was an Helper which generated
     * widgets, the actual instance created here is the Widget itself.
     * The problem solved, though, is the same: managing creation of widgets in the
     * middle of business logic.
     *
     * This class purpose is to generate blinking text in spite of all
     * usability recommendations. This is the Prototype.
     * As always, interfaces in php may be omitted. This is primary here for type
     * hinting.
     */
    interface BlinkingWidget
    {
    }
    
    /**
     * Implementation that generates html tied to a javascript library.
     * This is one ConcretePrototype.
     */
    class JavascriptWidget implements BlinkingWidget
    {
        public function initialize($text)
        {
            $this->_text = $text;
        }
    
        public function __toString()
        {
            return '<div dojoType="...">' . $this->_text . '</div>';
        }
    }
    
    /**
     * A collaborator for the next ConcretePrototype.
     */
    class ObjectTag
    {
        private $_html;
    
        public function setContent($html)
        {
            $this->_html = $html;
        }
    
        public function __toString()
        {
            return "<object>{$this->_html}</object>\n";
        }
    }
    
    /**
     * Implementation that generates html that loads a flash object.
     * This is one ConcretePrototype.
     */
    class FlashWidget implements BlinkingWidget
    {
        private $_objectTag;
    
        public function __construct(ObjectTag $objectTag)
        {
            $this->_objectTag = $objectTag;
        }
    
        public function initialize($text)
        {
            $this->_objectTag->setContent("<param name=\"text\">$text</param>");
        }
    
        public function __toString()
        {
            return (string) $this->_objectTag;
        }
    
        /**
         * When using the clone operator, php will perform a shallow copy of the
         * original object, duplicating references to the same collaborators.
         * Then this method will be called on the newly created object; it's time
         * to perform a cloning of the collaborators which cannot be shared with
         * the original instance.
         * This is NOT an override: it's a post-cloning hook which completes the 
         * new instance substituting some shallow copies with deep ones.
         */
        public function __clone()
        {
            $this->_objectTag = clone $this->_objectTag;
        }
    }
    
    /**
     * SECTION 2: a Client class which clones instances of BlinkingWidget.
     *
     * We cannot instantiate all the BlinkingWidgets in advance, so we need a base
     * one which will be cloned every time a new one is needed.
     */
    class LoginPage
    {
        private $_widget;
    
        public function __construct(BlinkingWidget $toClone)
        {
            $this->_widget = $toClone;
        }
    
        public function render()
        {
            $userId = uniqid('User ');
            // insert all the logic needed here...
            if (true or $complexBusinessLogicRules) {
                $widget = clone $this->_widget;
                $widget->initialize("Welcome, $userId");
                return (string) $widget;
            }
        }
    }
    
    $prototypeWidget = new FlashWidget(new ObjectTag);
    $page = new LoginPage($prototypeWidget);
    echo $page->render(), "\n";
    
    $page = new LoginPage(new JavascriptWidget);
    echo $page->render(), "\n";
    Theoretical notes
    • in languages where a Class object (meta programming) is available, the Prototype pattern is less important because Class objects are already standard prototypes. In Php, the most we can configure is a class name with a string, along with an array that represents a series of constructor options, so it can be considered as a practical solution.
    • main problem is implementing a clone() method, which should produce copies or references to collaborators, a difference that should be decided case-by-case (deep or shallow copies); php has a standard clone operator and __clone() magic method which are used in the code sample; I suggest to refer to the sample and the manual for more information.
    • after the cloning process, it is often suggested to add an initialize() method which allows for setting pieces of state which may differ from the prototype object; for instance, an id or a name field. This method should not be included in the Prototype interface or its parameters be put in the clone() method: first, php does not support cloning with parameters; second, different ConcretePrototypes will need different initialization values or no values at all.
    • in Javascript, object-oriented programming is prototype-based and not class-based. It means that, as a language feature, every new object is created by cloning a prototype. Class-based programming is often emulated by javascript frameworks.
    As for related creational patterns, Prototype and Abstract Factory are often in competition, but an Abstract Factory might use Prototype instances to create new ones, effectively hiding the cloning from the Client class.

    Prototype seems a very simple pattern but this post turned out as detail-rich one. Do you feel anything is missing? Add a comment.

      Monday, January 11, 2010

      Practical Php Patterns: Factory Method

      This is the third post from the Practical Php Pattern series, which will touch the majority of the known design patterns, with a special look at their application in a php context and code samples.

      The third creational pattern we will study is the Factory Method one.
      By definition a Factory Method is any method whose responsibility is creating an object, or providing a already existent instance of a particular class.
      Factory Methods are the seams which allow tuning of an instantiation; for example, to recycle already created objects or to introduce subclasses of the original Product.

      ConcreteCreators, subclasses of a Creator class, redefine the factory method forcing it to create a ConcreteProduct instead of a generic Product. The subclass term is used here extensively, also to indicate an interface's implementations; the Creator nickname shows that the role of the class in this pattern is creating the Product, but by no means its responsibility consists in creating it: the responsibility of Creator is to accomplish some tasks which requires fresh instances of Product to be created, as a side effect. The responsibility of actually instantiating a ConcreteProduct is usually left to the ConcreteCreators.
      This pattern has a strong affinity with the Abstract Factory one: usually every relevant method of the Abstract Factory is a Factory Method, but isolated Factory Methods can be used also in other situations. For instance, with the intention of having them overridden by subclasses, incorporating the factory in the class itself and having them called by Template Methods.
      Factory Methods may be moved out of their class in subsequent refactorings and evolve in an external Abstract Factory.

      PARTICIPANTS:
      • Product: the abstraction of the created object.
      • ConcreteProduct: a subclass or implementation of Product.
      • Creator: the base class, which declares an abstract or default Factory Method.
      • ConcreteCreator: a subclass of the Creator which overrides the Factory Method to return a ConcreteProduct.
      The code sample reprises the Abstract Factory example and implements the same functionality using only a simple Factory Method. The disadvantage is that subclassing is required to take advantage of this hook.
      <?php
      /**
       * SECTION 1: a WidgetHelper interface and two different implementations.
       *
       * This class purpose is to generate blinking text in spite of all
       * usability recommendations. This is the Product.
       * As always, interfaces in php may be omitted.
       */
      interface WidgetHelper
      {
          /**
           * @return string
           */
          public function generateHtml($text);
      }
      
      /**
       * Implementation that generates html tied to a javascript library.
       * This is one ConcreteProduct.
       */
      class JavascriptWidgetHelper implements WidgetHelper
      {
          public function generateHtml($text)
          {
              return '<div dojoType="...">' . $text . '</div>';
          }
      }
      
      /**
       * Implementation that generates html that loads a flash object.
       * This is one ConcreteProduct.
       */
      class FlashWidgetHelper implements WidgetHelper
      {
          public function generateHtml($text)
          {
              return '<object>
              <param name="text">' . $text . '</param>
              </object>';
          }
      }
      
      /**
       * SECTION 2: a Creator class which defines a seam to change the object it
       * creates during execution.
       *
       * Normally we would inject the chosen WidgetHelper to the Client class, but
       * since WidgetHelpers are created during the execution (basing on business
       * logic) we cannot instantiate them in advance and so we need an abstraction
       * on the creation process to allow reusing and overriding: the Factory Method
       * createWidgetHelper().
       */
      abstract class LoginPage
      {
          /**
           * @return WidgetHelper
           */
          public abstract function createWidgetHelper();
      
          /**
           * A Template Method which uses the Factory Method.
           */
          public function render()
          {
              $userId = uniqid('User ');
              // insert all the logic needed here...
              if (true or $complexBusinessLogicRules) {
                  $helper = $this->createWidgetHelper();
                  return $helper->generateHtml("Welcome, $userId");
              }
          }
      }
      
      /**
       * First subclass: creates Javascript-based helpers.
       * This is one ConcreteCreator.
       */
      class JavascriptLoginPage extends LoginPage
      {
          public function createWidgetHelper()
          {
              return new JavascriptWidgetHelper();
          }
      }
      
      /**
       * Second subclass: creates Flash-based helpers.
       * This is one ConcreteCreator.
       */
      class FlashLoginPage extends LoginPage
      {
          public function createWidgetHelper()
          {
              return new FlashWidgetHelper();
          }
      }
      
      $page = new FlashLoginPage();
      echo $page->render(), "\n";
      $page = new JavascriptLoginPage();
      echo $page->render(), "\n";
      The testability of code that follows this pattern is still nearly good as with an Abstract Factory; all it takes to mock the creation process is to subclass and override the factory method, which we would do anyway in the test suite with an external ConcreteFactory class and is a standard testing technique.
      A common misconception is a static version of the Factory Method, which is placed on a Product or ConcreteProduct class and provide a constructor with a fancy name. The original intent was having the method overridden, so if it is implemented as static the goal is not achieved; the trick is that the method should reside on the class that need the instantiation of Product objects, and not on the Product itself.
      Some versions even propose to maintain a static object pool managed by a static method in the Product class, which is dangerously-equivalent to filling some water bottles with gasoline and amassing them in the car trunk just in case the tank needs to be refilled, throw in a burning match and closing the trunk with the keys inside.
      Moreover, if the method has references to the subclasses of Product, they become all mutually coupled and depend the one on all the others, forcing to modify the base class in case a new subclass is added.
      In conclusion, a Factory Method is a non-static overridable creation method, which belongs to the class that needs to instantiate a Product (or to a class composed by it).

      Remember to comment and propose patterns for inclusion in this series!

      Saturday, January 09, 2010

      Php 5.3 on Sourceforge

      This week, since I had not found similar proposals, I posted an idea on the Sourceforge IdeaTorrent:
      Php 5.3 is not available on Project Web platform
      Php 5.3 is required by the Doctrine 2 ORM and will be probably required for Zend Framework 2.0; php projects should be able to develop for 5.3 without losing the availability of the project web platform for testing and demos.
      Sourceforge is one of the biggest hosting platforms for open source projects.
      The Project web platform is the web hosting space available for every project at http://PROJECTNAME.sourceforge.net, which can store sample instances of web applications, such as public demos or development checkouts.
      This platform provides a mysql database and php 5.2, but I think it's important to help open source projects adopting php 5.3 and its shiny new features, like namespaces and closures, whilst keeping example deployments on the sourceforge.net servers.
      If you also think php 5.3 would be a useful option on Sourceforge web hosting, vote for the solution or propose new ones on the IdeaTorrent. :)

      The Practical Php Patterns series will resume on next Monday.

      Friday, January 08, 2010

      Practical Php Patterns: Builder

      This is the second post from the Practical Php Pattern series, which will touch the majority of the known design patterns, with a special look at their application in a php context. A running code sample will be provided for each part of this series.

      Continuing the discussion on creational patterns, today we will introduce the Builder pattern, along with a Tree class php example.
      The Builder pattern's intent is to encapsulate the details (the new operators and other wiring) of the object creation process under a common interface. Though, the Builder can actually change the internal representation of an object, as it is not a black box.

      Complex object graphs which present some redundancy in construction (like Composite pattern implementations) can be simplified by factoring out most of the wiring in a Builder. In the example, a simple Tree object will be constructed by a DumbUnbalancedTreeBuilder, the ConcreteBuilder of this code sample.
      The point is to abstract away the actual instantiation and to construct an interface for the building process, which is leveraged by one or more Director classes. The interface can be explicit (Builder participant) or implicitly defined by the public methods of the ConcreteBuilder. Php's duck typing supports this indirect definition of interface when needed.

      Participants:
      - Director: class that composes a Builder to utilize its methods to control the creation process of the Product.
      - Builder: interface that presents a high-level abstraction on the actual object graph carving. GoF suggests to create a base abstract class with empty methods instead of an interface, to let the ConcreteBuilders redefine only the methods they are interested in.
      - ConcreteBuilder: implementation of the Builder.
      - Product: the final product of a ConcreteBuilder's work.

      This is the php code sample for this pattern.
      <?php
      /**
       * Tree implementation that contains one value and the references to the
       * left and right branches (other Tree objects).
       * This is our Product, which usually is not hidden with an interface
       * because of the very different Products that ConcreteBuilders create.
       */
      class Tree
      {
          private $_value;
          private $_left;
          private $_right;
      
          /**
           * @param integer
           */
          public function __construct($value)
          {
              $this->_value = $value;
          }
      
          public function getValue()
          {
              return $this->_value;
          }
      
          /**
           * @return Tree
           */
          public function getLeft()
          {
              return $this->_left;
          }
      
          public function setLeft(Tree $t)
          {
              $this->_left = $t;
          }
      
          /**
           * @return Tree
           */
          public function getRight()
          {
              return $this->_right;
          }
      
          public function setRight(Tree $t)
          {
              $this->_right = $t;
          }
      
          /**
           * Prints values visiting Tree with in-order traversal
           */
          public function dump()
          {
              $string = '';
              if ($this->_left) {
                  $string .= $this->_left->dump();
              }
              $string .= " $this->_value ";
              if ($this->_right) {
                  $string .= $this->_right->dump();
              }
              return $string;
          }
      }
      
      /**
       * ConcreteBuilder. You can extract an interface TreeBuilder, based on
       * its three public methods, if there are multiple implementations of this
       * participant.
       * This class encapsulates the necessary logic to insert new subtrees
       * in the right points, maintaining the ordering between values (in-order
       * representation).
       */
      class DumbUnbalancedTreeBuilder
      {
          private $_tree;
      
          public function reset()
          {
              $this->_tree = null;
          }
      
          public function addNumber($number)
          {
              $this->_tree = $this->_addTo($this->_tree, $number);
          }
      
          private function _addTo(Tree $tree = null, $number)
          {
              if ($tree === null) {
                  $tree = new Tree($number);
                  return $tree;
              }
      
              if ($number < $tree->getValue()) {
                  $tree->setLeft($this->_addTo($tree->getLeft(), $number));
              } else {
                  $tree->setRight($this->_addTo($tree->getRight(), $number));
              }
              return $tree;
          }
      
          public function getTree()
          {
              return $this->_tree;
          }
      }
      
      /**
       * A Director might encapsulate this sample code that uses the Builder.
       */
      $builder = new DumbUnbalancedTreeBuilder();
      $builder->addNumber(7);
      $builder->addNumber(1);
      $builder->addNumber(3);
      $builder->addNumber(5);
      $builder->addNumber(8);
      $builder->addNumber(6);
      $builder->addNumber(9);
      $builder->addNumber(5);
      $builder->addNumber(4);
      $builder->addNumber(2);
      echo $builder->getTree()->dump(), "\n";
      There are several differences between a Builder and an AbstractFactory: AbstractFactory is a black box which returns a complete object basing on previous configuration; it preserves the contract of an AbstractProduct. A Builder allows a step-by-step construction process to take place and provides a finer control over the single collaborators management.
      In the example, there is not a unique Tree in an application; an AbstractFactory would be good in returning always the same object again and again,relieving the Client class from the responsibility of choosing and configuring it. A Builder is instead good in allowing flexibility of the created object graph while hiding all unnecessary details and logic.
      Nothing prevents you to reference an AbstractFactory from a Builder, that instantiates the different parts of a Product, effectively separating logic (Builder) from new operators (ConcreteFactory).

      Did you like this article and the previous one? Please comment and suggest which patterns should be treated extensively in this series.

      Thursday, January 07, 2010

      Practical Php Patterns: Abstract Factory

      This is the first installment of the Practical Php Patterns series, which would touch the majority of the known design patterns, with a special look at their application in a php context. A running code sample will be provided for each part of this series, along with the theory and the terminology of each pattern.

      The patterns that will be discussed first, following the original GoF Design Patterns book approach, are the creational ones. Creating object graphs is an essential skill in object-oriented development and correctly addressing the bootstrap of the application and the object instantiation is part of the programming's complexity.

      The first pattern we will introduce is the Abstract Factory one, also known as Provider or simply as Factory, in its variant which does not include explicit interfaces.
      The major problem that creational patterns try to solve is that objects need collaborators: we often pass them in the constructor of a Client class to aid decoupling, as every class should know only what it really needs to get its job done. With the verb know I mean that they just know that the other part exist at all.
      The fundamental principle of asking for things (Dependency Injection) substitutes the naive approach of looking for things or creating them.
      A Client is simply the generic name of an high-level class which makes use of the collaborators, and occurs frequently in the design patterns Ubiquitous Language. These generic names are known as participants in a pattern, and allow developers to discuss a pattern without referring to a particular implementation.

      Dependency Injection prescribes to ask for collaborators in the constructor of a Client, or via setters that accepts the collaborator as a parameter to store it for later use. Most of the times collaborators are created at the startup of the application/script, before their Client, to satisfy the dependency.
      The fallacy here (which is not really a fallacy, since it works most of the time) is evident when the collaborators assume shorter lifecycles. Often objects are created as a result of business logic (a Post or Forum instance, for example, in the middle of a php script), and by the way with a shorter lifecycle of the object that creates them. As another example, they can be lazily created only when necessary.
      In php's case, lazy creation is mandatory because there is no need to create all kinds of helper objects on every single http request. You certainly do not expect to define all your buttons, links and inputs at the startup in a single object graph: their creation is regulated by an analysis of the request parameters and of the database state.

      Though, you may want to govern which kind of objects are created: if the names of the ConcreteProduct classes are hardcoded in the Client, you lose the flexibility of Dependency Injection, which provide advantages like real unit testing and decoupled design.
      The AbstractFactory solution consists in encapsulating the creation process behind an AbstractFactory interface, which may be implemented by how many different ConcreteFactory classes are needed. One of this ConcreteFactory is then injected in the Client that will call its methods to create the objects, when ready.

      Pattern participants:
      • AbstractProduct: the interface for the collaborator
      • ConcreteProduct: an implementation of the collaborator
      • AbstractFactory: the interface for the factory that builds an AbstractProduct
      • ConcreteFactory: an implementation of the AbstractFactory, to be injected in the Client
      • Client: the final user class of the collaborator
      I will finally let the code speak now.
      <?php
      /**
       * SECTION 1: a WidgetHelper interface and two different implementations.
       * Normally we would inject the chosen WidgetHelper to the Client class, but
       * creating all possible helpers renders the constructor enormous, whilst we
       * are not even sure that they would be actually used.
       *
       * This class purpose is to generate blinking text in spite of all
       * usability recommendations. This is the AbstractProduct.
       */
      interface WidgetHelper
      {
          /**
           * @return string
           */
          public function generateHtml($text);
      }
      
      /**
       * Implementation that generates html tied to a javascript library.
       * This is one ConcreteProduct.
       */
      class JavascriptWidgetHelper implements WidgetHelper
      {
          public function generateHtml($text)
          {
              return '<div dojoType="...">' . $text . '</div>';
          }
      }
      
      /**
       * Implementation that generates html that loads a flash object.
       * This is one ConcreteProduct.
       */
      class FlashWidgetHelper implements WidgetHelper
      {
          public function generateHtml($text)
          {
              return '<object>
              <param name="text">' . $text . '</param>
              </object>';
          }
      }
      
      /**
       * SECTION 2: since we are not going to pass the instances of WidgetHelper to
       * the Client class (because they do not exist yet), we need an interface
       * for the creator of these WidgetHelpers, which results in an Abstract Factory.
       * This is the collaborator which would be injected in the client.
       */
      interface WidgetHelperAbstractFactory
      {
          /**
           * @return Widget
           */
          public function createWidgetHelper();
      }
      
      /**
       * First implementation: creates a Javascript-based helper.
       * This is one ConcreteFactory.
       */
      class JavascriptHelperFactory implements WidgetHelperAbstractFactory
      {
          public function createWidgetHelper()
          {
              return new JavascriptWidgetHelper();
          }
      }
      
      /**
       * Second implementation: creates a Flash-based helper.
       * This is one ConcreteFactory.
       */
      class FlashHelperFactory implements WidgetHelperAbstractFactory
      {
          public function createWidgetHelper()
          {
              return new FlashWidgetHelper();
          }
      }
      
      /**
       * Third implementation: creates a random type of helper.
       * Note that commonly the WidgetHelperAbstractFactory interface will require
       * methods to create all the helpers needed. It's up to the single
       * ConcreteFactory implementation to instantiate a family of objects
       * (flash|javascript html bindings generators) or another,
       * or even a mixture of different families or whatever.
       * Dependency Injection containers take this approach to the extreme,
       * providing automatically configurable factories for every
       * concrete class.
       */
      class RandomHelperFactory implements WidgetHelperAbstractFactory
      {
          public function createWidgetHelper()
          {
              srand();
              if (rand() > 0.5) {
                  return new JavascriptWidgetHelper();
              } else {
                  return new FlashWidgetHelper();
              }
          }
      }
      
      /**
       * SECTION 3: a Client class that uses an AbstractFactory to create Widget
       * instances whenever it wants.
       * Note that this class only depends on abstractions (AstractFactory and its
       * AbstractProduct). However, since php has no compile-time dependencies,
       * an interface for the Products or the Factories is not mandatory.
       */
      class LoginPage
      {
          private $_widgetFactory;
      
          public function __construct(WidgetHelperAbstractFactory $factory)
          {
              $this->_widgetHelperFactory = $factory;
          }
      
          public function render()
          {
              $userId = uniqid('User ');
              // insert all the logic needed here...
              if (true or $complexBusinessLogicRules) {
                  $helper = $this->_widgetHelperFactory->createWidgetHelper();
                  return $helper->generateHtml("Welcome, $userId");
              }
          }
      }
      
      $page = new LoginPage(new FlashHelperFactory());
      echo $page->render(), "\n";
      $page = new LoginPage(new JavascriptHelperFactory());
      echo $page->render(), "\n";
      
      Often factories in php applications are applications of this pattern without the abstract trait, with a developed dependency towards a ConcreteFactory. With the same pragmatism, different kind of collaborators which are highly related can be placed in the same ConcreteFactory, by adding other creation methods.
      I hope you now grasp how to build objects at the right time in your application, as lazily as you want, without depending on concrete classes.
      Tomorrow we will discuss another creational pattern, the Builder one.

      Don't forget to comment if you like the post or you feel something is missing. Feedback can drive the evolution of this series of articles.

      ShareThis