How to implement a decorator in PHP?

decorator, oop, php

Solution

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.

Problem

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.

Original source

Related problems