How to implement a decorator in PHP?

后端 未结 5 566
灰色年华
灰色年华 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:48

    None of these answers implements Decorator properly and elegantly. mrmonkington's answer comes close, but you don't need to use reflection to enact the Decorator pattern in PHP. In another thread, @Gordon shows how to use a decorator for logging SOAP activity. Here's how he does it:

    class SoapClientLogger
    {
        protected $soapClient;
    
        // this is standard. Use your constuctor to set up a reference to the decorated object.
        public function __construct(SoapClient $client)
        {
            $this->soapClient = $client;
        }
    
        ... overridden and / or new methods here ...
    
        // route all other method calls directly to soapClient
        public function __call($method, $args)
        {
            // you could also add method_exists check here
            return call_user_func_array(array($this->soapClient, $method), $args);
        }
    }
    

    And he's a slight modification where you can pass the desired functionality to the constructor:

    class Decorator {
    
        private $o;
    
        public function __construct($object, $function_name, $function) {
            $this->o = $object;
            $this->$function_name = $function;
        }
        public function __call($method, $args)
        {
            if (!method_exists($this->o, $method)) {
                throw new Exception("Undefined method $method attempt in the Url class here.");
            }
            return call_user_func_array(array($this->o, $method), $args);
        }   
    }
    

提交回复
热议问题