Design Patterns

Summary

What are design patterns?

"Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice."

– Christopher Alexander, talking about buildings and towns

What are design patterns?

What are design patterns?

What do patterns not do?

Elements of a pattern

When to use them

Common Patterns

Abstract Factory

require_once 'DB.php';

$type = 'mysql';
$options = array(...);
$dbh = &DB::connect($type, $options);

Implementing Abstract Factory

    function &factory($type)
    {
        @include_once("DB/${type}.php");

        $classname = "DB_${type}";

        if (!class_exists($classname)) {
            return PEAR::raiseError(null, DB_ERROR_NOT_FOUND,
                                    null, null, null, 'DB_Error', true);
        }

        return $obj =& new $classname;
    } 

Singleton

Implementing Singleton

    function &singleton()
    {
        static $registry;

        if (!isset($registry)) {
            $registry = new Registry();
        }

        return $registry;
    }

Implementing Singleton in PHP5

PHP5's improved object model allows a better singleton implementation:

    /**
     * The one instance.
     */
    static private $instance = false;

    /**
     * Make the constructor private.
     */
    private function __construct() {}

    /**
     * Use this static method to get at the one instance.
     */
    static public function singleton()
    {
        if (!self::$instance) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }

Observer

Implementing Observer: Subject

    function attach(&$observer)
    {
        $this->_observers[$observer->getId()] =& $observer;
    }

    function detach(&$observer)
    {
        unset($this->_observers[$observer->getId()]);
    }

    function notify()
    {
        foreach ($this->_observers as &$observer) {
            $observer->update($this);
        }
    }

Implementing Observer: Observer

    function update(&$subject)
    {
        // Do what needs to be done.
    }

Model/View/Controller

MVC: Model/View

MVC: View Compositing

MVC: View/Controller

PHP Implementations