Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

oop - How to implement a decorator in PHP?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(array('e', 'i', 'l', 't', 'o'), array(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...