Tom Rawcliffe has posted the latest installment of his look at design patterns in PHP. This time his focus is on the Decorator pattern.
Continuing my series on PHP design patterns, today itâ€™s the turn of the Decorator. In contrast to last weekâ€™s Strategy Pattern which is used to change the â€œgutsâ€ of a class, the Decorator Pattern is used to extend the behavior of a class with different functionality at run time. This is achieved by implementing a â€œdecoratorâ€ class that implements the same interface as the object that you wish to â€œdecorateâ€ and wraps itâ€™s content.
The Decorator pattern lets you "decorate" your objects with additional features. He illustrates with a sample "Property" class (that implements an interface) that he wants to extend past the normal property handling. He add a "PropertyDecorator" to the mix that lets it use deocrators for uppercasing and padding the string. There's an example script included at the end that shows how to put it all to use.