コントローラからアクションヘルパーを実行する
例えば、 Redirector ヘルパーを利用したい場合、例えばコントローラ内から以下のように使用します。
<?php $this->_helper->redirector($action, $controller, $module, $params);
このように、 $this->_helper-> に続けて使用したいヘルパー名を続ける事で使用可能です。
さらに、 Redirector ヘルパーのもつその他のメソッドを使用したい場合は、以下のように、メンバとして呼び出して、使用したいメソッドを使用する事で実現可能です。
<?php $this->_helper->redirector->gotoRoute($urlOptions, $name, $reset, $encode);
内部的な話
ここから、実際どのようにして動作しているのか、内部処理を追って行きます。*1
<?php // Zend/Controller/Action.php abstract class Zend_Controller_Action implements Zend_Controller_Action_Interface { public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) { $this->setRequest($request) ->setResponse($response) ->_setInvokeArgs($invokeArgs); $this->_helper = new Zend_Controller_Action_HelperBroker($this); $this->init(); } }
コントローラの抽象クラス、コンストラクタにて $this->_helper に Zend_Controller_Action_HelperBroker のインスタンスが代入されます。
<?php // Zend/Controller/Action/HelperBroker.php class Zend_Controller_Action_HelperBroker { 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); } public function __get($name) { return $this->getHelper($name); } }
コントローラからヘルパーがメソッドとして呼ばれた場合、ヘルパーブローカーのマジックメソッド __call() が呼ばれ、指定されたヘルパーの direct() メソッドがコールされます。
そして、メンバとして呼ばれた場合、ゲッター __get() が呼ばれ、指定されたヘルパーのインスタンスが返されます。
ですので、ヘルパーのもつその他のメソッドが利用可能となるわけです。
*1:説明に不要な部分は記述を省きます。