PHP Decorator Pattern

Posted by Tully on Wed 02 December 2009

I read PHP Objects, Patterns, and Practice, Second Edition a while back but nothing really kicked in. I have yet again started studying various design patterns. I started started reading Head First Design Patterns and feel this book is easier to understand. I also recently finished the Head First SQL book which I enjoyed.

Today I have been studying the Decorator Pattern.

Wikipedia defines the Decorator Pattern as follows:

In object-oriented programming, the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing object dynamically".

Basically what it allows is for you to extend a class without being part of that family. You create a Decorator class and then extend onto that class.

Decorator Pattern in PHP

<?php
/*
* Example of Decorator Pattern in PHP
*
*/
class ReadStr {
    protected $str;

    function __construct($str) {
        $this->str = $str;
    }

    function display() {
        return $this->str;
    }
}

class StrDecorator extends ReadStr {
    protected $str;
    protected $readStr;

    function __construct(ReadStr $readStr) {
        $this->readStr = $readStr;
        $this->str = $this->readStr->display();
    }

    function display() {
        return $this->str;
    }
}

class StrToUpperDecorator extends StrDecorator {
    private $strDecorator;

    function __construct(StrDecorator $strDecorator) {
        $this->strDecorator = $strDecorator;
        $this->stringToUpper();
    }

    function stringToUpper() {
        $this->strDecorator->str = strtoupper($this->strDecorator->str);
    }

}

class StrReverseDecorator extends StrDecorator {
    private $strDecorator;

    function __construct(StrDecorator $strDecorator) {
        $this->strDecorator = $strDecorator;
        $this->stringReverse();
    }

    function stringReverse() {
        $this->strDecorator->str = strrev($this->strDecorator->str);
    }
}

$readStr = new ReadStr('Decorator Pattern!');
$decorator = new StrDecorator($readStr);
echo $decorator->display() . "n";
$strToUpper = new StrToUpperDecorator($decorator);
echo $decorator->display() . "n";
$strReverse = new StrReverseDecorator($decorator);
echo $decorator->display();