开发者

Zend:does action helper's init method passes variables to layout view?

开发者 https://www.devze.com 2023-03-07 06:01 出处:网络
PROBLEM: I can\'t pass my variables to my custom layout fromaction helper\'s init method. I have this action helper \"My_Action_Helper_Initializer\":

PROBLEM: I can't pass my variables to my custom layout from action helper's init method.

I have this action helper "My_Action_Helper_Initializer":

class My_Action_Helper_Initializer extends Zend_Controller_Action_Helper_Abstract
{
 public function init()
 {
  $controller=$this->getActionController();
  //variable passed to controller's view
  $controller->view->flop="FLOOP!!";
  //variable passed to controller
  $controller->boom="BOOM!!";
 }
}

In my controller "IndexController":

class IndexController extends Zend_Controller_Action
{ 
  public function indexAction()
  {
    //print the variable passed from action helper
    echo $this->boom;
  }
}   

then in my "layout.phtml":

//print variable passed from action helper
echo $this->flop;
  • So the "boom" variable echoed out by controller action is shown correctly.

  • The "flop" variable (passed to my layout) is not shown.

    QUESTION: Why the variable passed to controlle开发者_高级运维r action is correctly output while the other one passed to the layout view is not?

Thanks

Luca


When your helper's init() called, ViewRenderer's init() wasn't yet. This is because of order in helpers stack.

If you enable strict standards error reporting, you should see something like this in your helper "Creating default object from empty value in ..."

You should consider moving your code to preDispatch() hook as init() method should be used for helper initialization.

To get view instance for controller:

function getView()
{
    $controller = $this->getActionController();
    if($view = $controller->view) {
        return $view;
    }

    if($this->getFrontController()->getParam('noViewRenderer') {
        return $controller->initView();//this view instance will not be used in Zend_Layout!
    }
    $vr = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
    return $vr->initView();      

}

if you want to pass parameter to layout, then use

$view = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->initView();


Action helpers are called so because they are a way to avoid code duplication in actions. Everything you do in an action helper is available to the actions but not to the view. That's the normal behaviour of actions, as long as you don't pass something to the view, the view doesn't know it. If you want to avoid code duplication in your views, create view helpers.

Sometimes it can make sense to create an action helper and a corresponding view helper.

--

preDispatch works() while init() doesn't because with init you're not actually hooking into the dispatch process.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号