Suppose there is a class called "Class_A
", it has a member function called "func
".
I want the "func
" to do some extra work by wrapping Class_A
in a decorator class.
$worker = new Decorator(new Original());
Can someone give an example? I've never used OO with PHP.
Is the following version right?
class Decorator
{
protected $jobs2do;
public function __construct($string) {
$this->jobs2do[] = $this->do;
}
public function do() {
// ...
}
}
The above code intends to put some extra work to a array.
I wanted to use decoration to encourage colleagues to use caching more, and inspired by the nice Python syntax experimented with PHP reflection to fake this language feature (and I have to stress 'fake'). It was a useful approach. Here's an example:
Better examples with caching examples here: https://github.com/mrmonkington/EggCup/
I would suggest that you also create a unified interface (or even an abstract base class) for the decorators and the objects you want decorated.
To continue the above example provided you could have something like:
Then of course modify both
Text
andLeetText
to implement the interface.Why use an interface?
Because then you can add as many decorators as you like and be assured that each decorator (or object to be decorated) will have all the required functionality.
A key and unique feature of the Decorator is that one abstract class extends another. The Decorator participant is both a wrapper for and extends the Component participant.
I believe that this is the only pattern where this happens in the Gang of Four catalog. The Decorator makes it easy to add properties to an object without changing the object. For a simple, accurate and clear example see:
http://www.php5dp.com/php-decorator-design-pattern-accessorizing-your-classes/#more-32
That is pretty easy, especially in a dynamically typed language like PHP:
You may want to have a look at the wikipedia article, too.
None of these answers implements
Decorator
properly and elegantly. mrmonkington's answer comes close, but you don't need to use reflection to enact theDecorator
pattern in PHP. In another thread, @Gordon shows how to use a decorator for logging SOAP activity. Here's how he does it:And he's a slight modification where you can pass the desired functionality to the constructor: