Pass a variable from postDispatch() to view instan

2019-08-02 19:47发布

问题:

I have a controller plugin with postDispatch() hook, and there I have a $variable.

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?

回答1:

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.



回答2:

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



回答3:

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>