HomePHP Page 3 - An Introduction to Using the Decorator Pattern with PHP
Defining the structure of a Decorator object - PHP
A decorator class allows you to add more capacity to an existing class while leaving the original class untouched. It has certain advantages over inheritance, as you will learn in this first article of a three-part series.
As you learned in the previous section, once the base “StringSaver” class has been defined, creating a decorator class is indeed a straightforward task to perform. Now, with reference to extending the existing functionality of the “StringSaver” class, suppose that you want to manipulate its $str property, in many creative and clever ways (I’m just kidding), such as uppercasing and lowercasing it. Sounds pretty cool, right?
Okay, in order to do that, I’m going to define a decorator class which will take the $str property of the base class and assign it as its own property. In this way it will act like a programmatic bridge for further decorators.
As usual, theory should be supported by the corresponding hands-on examples, so below is the definition of the “StringDecorator” class. Please examine its signature:
class StringDecorator{ protected $strsaver; public $str; // pass 'StringSaver' object to constructor public function __construct(StringSaver $strsaver){ $this->strsaver=$strsaver; // retrieve string from original 'StringSaver' object $this->resetString(); } // obtain string from 'StringSaver' object // thus the original property remains the same public function resetString(){ $this->str=$this->strsaver->getString(); } // return string to calling code public function displayString(){ return $this->str; } }
If you take a look at the above class, then you’ll realize that there are some interesting things worth noting. First, the “StringDecorator” class accepts an object of type “StringSaver” as its unique parameter, which is assigned as a class property inside the constructor.
However, the most relevant thing happens in relation with the “resetString()” method, since it uses the “getString()” method that belongs to the “StringSaver” class and obtains its $str property. While this is a simple concept, it demonstrates how to build a class that takes up the properties of a base class without modifying its original structure. Now, do you see how a decorator class fits into the whole picture?
All right, at this point, the “StringDecorator” class is limited to taking the $str property from the base class, but aside from that, it’s not doing anything else. Therefore, it’s time to leap forward and see how the original $str property can be uppercased and lowercased by deriving a couple of concrete subclasses from the “StringDecorator” class.
That’s exactly the subject of the next section, so I recommend you jump straight into it and keep learning more.