How to implement a decorator in PHP?

后端 未结 5 569
灰色年华
灰色年华 2020-12-01 06:09

Suppose there is a class called \"Class_A\", it has a member function called \"func\".

I want the \"func\" to do some extra w

5条回答
  •  半阙折子戏
    2020-12-01 06:52

    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.

提交回复
热议问题