__call等效于公共方法

Bob*_*ley 10 php oop zend-framework public-method

我有一个用于与我的网络应用程序交互的API,由一个类定义.每个可公开访问的方法都需要在运行前完成身份验证.我不想在每个方法中反复使用相同的行,而是想使用magic __call函数.但是,它只适用于私有或受保护的方法,并且我需要公开才能使用Zend_Json_Server.

class MY_Api
{
  public function __call($name, $arguments)
  {
    //code here that checks arguments for valid auth token and returns an error if false
  }

  public function myFunction($param1, $param2, $param3)
  {
    //do stuff when the user calls the myFunction and passes the parameters
    //this function must remain public so that Zend_Json_Server can parse it
    //but I want it intercepted by a magic method so that the authentication
    //can be checked and the system bails before it even gets to this function.
  }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能挂钩这些公共函数并可能在它们被调用之前取消它们的执行?

Jan*_*nen 7

__call实际上适用于所有方法,包括公共方法.但是,如果公共方法已经存在,它将无法工作的原因是因为类外的代码已经可以访问公共成员.__call仅对调用代码无法访问的成员调用.

据我所知,除了使用某种装饰模式外,实际上没有选择去做你想要的东西:

class AuthDecorator {
    private $object;

    public function __construct($object) {
        $this->object = $object;
    }

    public function __call($method, $params) {
        //Put code for access checking here

        if($accessOk) {
            return call_user_func_array(array($this->object, $method), $params);
        }
    }
}

$api = new MY_Api();
$decoratedApi = new AuthDecorator($api);

//any calls to decoratedApi would get an auth check, and if ok, 
//go to the normal api class' function
Run Code Online (Sandbox Code Playgroud)