I’m learning Zend Framework at the moment and came across the following syntax.
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);
}
}
In Zend Framework the direct() method in this class can be called using the following syntax:
$this->_helper->redirector('index','index');
Where redirector is an object(!) in the _helper object, which is inside the controller object, in which we call the method. The syntactic sugar here is that you can just pass parameters to the object instead of to the method, which we would write like so:
$this->_helper->redirector->gotoSimple('index','index');
..which is all fine and dandy ofcourse.
Here’s my question: is this direct() method standard in OO PHP? Or is this functionality built into Zend Framework?
I can’t find any documentation on this.
Thanks!
It is functionality build into Zend Framework.
The
$_helpersproperty in the Controller instance holds anAction_HelperBrokerinstance. This instance implements PHP’s magic__callmethod. When you call a method that does not exist on that instance, it will try to use the method name to fetch a helper of the same name and calldirect()on it (if possible). See code below.From
Zend_Controller_ActionFrom
Zend_Controller_Action_HelperBrokerThe Helper Broker also implement the magic
__getmethod, so when you try to access a property that does not exist, the broker will use the property name as an argument togetHelper()Please be aware that magic methods are not meant as a replacement to a proper API. While you can use them as shown above, calling the more verbose
is often the much faster alternative.