开发者

Pass a variable from postDispatch() to view instance in Zend Framework

开发者 https://www.devze.com 2022-12-24 04:01 出处:网络
I have a controller plugin with postDispatch() hook, and there I have a $var开发者_JAVA技巧iable.

I have a controller plugin with postDispatch() hook, and there I have a $var开发者_JAVA技巧iable.

How to pass this variable to the view instance?

I tried Zend_Layout::getMvcInstance()->getView(), but this returns new view instance (not the application resource). The same with $bootstrap->getResource('view').

I don't want to pass it as a request param.

Now, as a workaround I do it using Zend_Registry.

But, is it the best way?


in the plugin:

class App_Plugin_MyPlugin extends Zend_Controller_Plugin_Abstract{


public function preDispatch (Zend_Controller_Request_Abstract $request){
    $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
    $viewRenderer->setNeverRender(true);
}

public function postDispatch(Zend_Controller_Request_Abstract $request){
   $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
   $view = $viewRenderer->view;
   $view->variable = 'new value';
   $viewRenderer->render();

}

}

In the controller:

class IndexController extends Zend_Controller_Action {

  public function indexAction() {

    $this->view->variable = 'value';

  }

}

In the view script:

<?php echo $this->variable; ?>

The output is: new value


I've been using the ViewRenderer action helper to get the view when I need it. It seems to be the most common way that Zend classes access the view object.

So, in the controller plugin:

class App_Controller_Plugin_ViewSetup extends Zend_Controller_Plugin_Abstract {

  public function postDispatch() {

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

    echo $view->variable;

    $view->variable = 'Hello, World';

  }

}

In the controller:

class IndexController extends Zend_Controller_Action {

  public function indexAction() {

    $this->view->variable = 'Go away, World';

  }

}

In the view script:

<?php echo $this->variable; ?>

The output is: Go away, WorldGo away, World

It seems like the problem is that the view script renders before the postDispatch() method is called, because this does return the main view object.


class ZFExt_Controller_Plugin_Passvar extends Zend_Controller_Plugin_Abstract 
{
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {

        $view = Zend_Controller_Front::getInstance()
                      ->getParam('bootstrap')
                      ->getResource('view');
        $view->variable = 'Hi there';
    }
}

Then in the view script

<p><?php echo $this->variable; ?></p>
0

精彩评论

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

关注公众号