📜 ⬆️ ⬇️

Implementing a decorator design pattern in PHP

I suppose the decorator himself as well as the reasons for which the use of this template is preferable to classical inheritance is not needed in the description. If you wish, you can read about it in the English or Russian Wikipedia. image Therefore, the article itself is just my thoughts on one of the possible implementations of this pattern, namely dynamic decoration as opposed to the widely used static decoration technique.

The advantage of dynamic decoration over static is the lack of the need to create special classes of decorators. In this case, all that is needed for the PHP class to be decorated is to use the appropriate impurity.

In the English Wikipedia article on the decorator (link above) there is a Java example of using static decoration in the implementation of window intefles. By analogy of that example, but without using decorator classes:

class Window { use TDecorator; private $title; function __construct($title) { $this->title = $title; } function draw() { // Draws window below // ... // Draws decorations. $this->renderDecoration('draw'); } } class VerticalScrollbar { use TDecoration; private $vWidth; private $vHeight; function __construct($width, $height) { $this->vWidth = $width; $this->vHeight = $height; } function draw() { echo 'Drawing vertical scrollbar for the window "' . $this->title . "\"\n"; echo 'Width: ' . $this->vWidth . "px\n"; echo 'Height: ' . $this->vHeight . "px\n"; } } // Decorates window with a vertical scrollbar. $wnd = new Window('My application'); $wnd->decorateWithObject(new VerticalScrollbar(20, 20)); $wnd->draw(); 

When decorating one object by another, it gains access not only to all its public and private methods, but also to properties along with their values. We can say that in this way the VerticalScrollbar class inherits the Window class, but only for a single object.
')
In addition to decorating one object by another, it is also easier to add new behavior:

 class Integer { use TDecorator; protected $value; function __construct($value) { $this->value = intval($value); } } $integer = new Integer(9); $integer->decorateWith('isOdd', function() { return (boolean) ($this->value % 2); }); echo $integer->isOdd(); // echoes true 

The implementation of the decorator as an impurity can be found here .

I hope this is a small article someone will be useful.

Source: https://habr.com/ru/post/166237/


All Articles