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 have started reading “Head First Design Patterns” and feel this book is easier to understand. I also recently finished the “Head Fist SQL” book which was written very well.
So today I have been studying the Decorator Pattern. Wiki defines it 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. Below is a simple example in PHP of the pattern
<?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";
span>$strToUpper = new StrToUpperDecorator($decorator);
echo $decorator->display() . "n";
$strReverse = new StrReverseDecorator($decorator);
echo $decorator->display();