Design Patterns

Table of Contents

  1. Design Patterns
    1. What are design patterns?
    2. What do patterns not do?
    3. When to use them
    4. Common Patterns
      1. Abstract Factory
        1. Implementing Abstract Factory
      2. Singleton
        1. Implementing Singleton
        2. Implementing Singleton in PHP5
      3. Observer
        1. Implementing Observer: Subject
        2. Implementing Observer: Observer
      4. Model/View/Controller
        1. MVC: Model/View
        2. MVC: View Compositing
        3. MVC: View/Controller
    5. PHP Implementations
    6. Some Resources

TODO: add more from the kongress2002-design_patterns presentation

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 do patterns not do?

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

Some Resources