我目前正在学习 Zend Framework 并遇到了以下语法。
class Zend_Controller_Action_Helper_Redirector extends Zend_Controller_Action_Helper_Abstract
{
/**
* Perform a redirect to an action/controller/module with params
*
* @param string $action
* @param string $controller
* @param string $module
* @param array $params
* @return void
*/
public function gotoSimple($action, $controller = null, $module = null, array $params = array())
{
$this->setGotoSimple($action, $controller, $module, $params);
if ($this->getExit()) {
$this->redirectAndExit();
}
}
/**
* direct(): Perform helper when called as
* $this->_helper->redirector($action, $controller, $module, $params)
*
* @param string $action
* @param string $controller
* @param string $module
* @param array $params
* @return void
*/
public function direct($action, $controller = null, $module = null, array $params = array())
{
$this->gotoSimple($action, $controller, $module, $params);
}
}
在 Zend Framework 中,可以使用以下语法调用此类中的 direct() 方法:
$this->_helper->redirector('index','index');
其中 redirector 是 _helper 对象中的对象 (!),它位于 Controller 对象内,我们在其中调用方法。这里的语法糖是你可以只将参数传递给对象而不是方法,我们会这样写:
$this->_helper->redirector->gotoSimple('index','index');
..这当然很好,很花花公子。
这是我的问题:这个 direct() 方法是 OO PHP 中的标准吗?或者此功能是否内置于 Zend Framework 中? 我找不到关于此的任何文档。
谢谢!
最佳答案
它是 Zend Framework 中内置的功能。
Controller 实例中的 $_helpers
属性包含一个 Action_HelperBroker
实例。这个实例实现了 PHP's magic __call
method .当您调用该实例上不存在的方法时,它将尝试使用该方法名称来获取同名的帮助程序并对其调用 direct()
(如果可能)。请参阅下面的代码。
来自 Zend_Controller_Action
/**
* Helper Broker to assist in routing help requests to the proper object
*
* @var Zend_Controller_Action_HelperBroker
*/
protected $_helper = null;
来自 Zend_Controller_Action_HelperBroker
/**
* Method overloading
*
* @param string $method
* @param array $args
* @return mixed
* @throws Zend_Controller_Action_Exception if helper does not have a direct() method
*/
public function __call($method, $args)
{
$helper = $this->getHelper($method);
if (!method_exists($helper, 'direct')) {
require_once 'Zend/Controller/Action/Exception.php';
throw new Zend_Controller_Action_Exception('Helper "' . $method . '" does not support overloading via direct()');
}
return call_user_func_array(array($helper, 'direct'), $args);
}
Helper Broker 还实现了神奇的 __get
方法,因此当您尝试访问不存在的属性时,代理将使用属性名称作为 getHelper() 的参数
/**
* Retrieve helper by name as object property
*
* @param string $name
* @return Zend_Controller_Action_Helper_Abstract
*/
public function __get($name)
{
return $this->getHelper($name);
}
请注意,魔术方法并不能替代适当的 API。虽然您可以如上所示使用它们,但调用更冗长的
$this->_helper->getHelper('redirector')->gotoSimple('index','index');
通常是更快的选择。
关于php - 方法语法 "public function direct(){}"在 PHP 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4058751/