How to implement a decorator in PHP?

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:

interface IDecoratedText
{
    public function __toString();
}

Then of course modify both Text and LeetText to implement the interface.

class Text implements IDecoratedText
{
    // same implementation as above
}

class LeetText implements IDecoratedText
{    
    protected $text;

    public function __construct(IDecoratedText $text) {
        $this->text = $text;
    }

    public function __toString() {
        return str_replace(['e', 'i', 'l', 't', 'o'], [3, 1, 1, 7, 0], $this->text->toString());
    }

}

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.

Leave a Comment

error code: 523