在每个实例方法调用之前和之后执行回调?

时间:2012-01-15 22:38:01

标签: php function callback

我在许多对象之间有一个共享的$sdk对象引用(它是Facebook PHP SDK)。我需要在函数调用的最开始时保存访问令牌,并在$this->sdk->api调用后恢复。请参阅示例getAlbums()函数。

如何在每个FBItem实例上的每个函数调用之前/之后自动执行回调

abstract class Item
{
   protected $id, $sdk, $auth;    

   public function __construct(Facebook $sdk, $auth = null)
   {   $this->sdk = $sdk; $this->auth = $auth;   }

   public function getAlbums() // Require access token change
   {
       // Am i FBUser or FBPage? Call setAccessToken to set auth
       $backup = $this->sdk->getAccessToken();
       $this->sdk->setAccessToken($auth ?: $backup);

       $as = array();
       $rs = $this->sdk->api(sprintf('/%s/albums', $this->id));
       foreach($rs['data'] as $i) $as[] = new Album($this->sdk, $this->auth);

       // Restore previous token backup
       $this->sdk->setAccessToken($backup);
   }

}

class User extends Item
{
   $ps = array(); $rs = $this->sdk->api(sprintf('/%s/accounts', $this->id));

   foreach($rs['data'] as $i) $ps[] = new Page($this->sdk, $i['access_token']);

   return $ps;
}

class Page extends Item { }

1 个答案:

答案 0 :(得分:2)

可能唯一的方法(不使用php rootkit或重写整个类)就是准备这样的包装器:

class FBItemWrapper {
    public $item = new FBItem();

    public function __call( $functionName, $args){
        // Pre callback
        $result = call_user_func_array( array( $this->item, $functionName), $args);
        // Post callback
        return $result;
    }
}

您可以动态设置对象,这样一个Wrapper就足够了。