How to implement a decorator in PHP?

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

    I wanted to use decoration to encourage colleagues to use caching more, and inspired by the nice Python syntax experimented with PHP reflection to fake this language feature (and I have to stress 'fake'). It was a useful approach. Here's an example:

    class MrClass { 
      /**
       * decoratorname-paramname: 50
       * decoratorname-paramname2: 30
       */
       public function a_method( $args ) {
         // do some stuff
       }
    }
    
    
    class DecoratorClass {
      public function __construct( $obj ) {
         $this->obj = $obj;
         $this->refl = new ReflectionClass( $obj );
      }
      public function __call( $name, $args ) {
        $method = $this->refl->getMethod( $name );
        // get method's doccomment
        $com = trim( $method->getDocComment() );
        // extract decorator params from $com
        $ret = call_user_func_array( array( $this->obj, $name), $args );
        // perhaps modify $ret based on things found in $com
        return $ret;
    }
    

    Better examples with caching examples here: https://github.com/gamernetwork/EggCup

提交回复
热议问题