Getting View Object from within a Zend Controller plugin

9.5k views Asked by At

In my controller, I have a postDispatch to consolidate my FlashMessenger messages:

public function postDispatch()
{       
    $messages = $this->_helper->getHelper ( 'FlashMessenger' )
        ->getMessages ();

    if ( $this->_helper->getHelper ( 'FlashMessenger' )
        ->hasCurrentMessages () )
    {
        $messages = array_merge ( $messages, $this->_helper->getHelper ( 'FlashMessenger' )
            ->getCurrentMessages () );
        $this->_helper->getHelper ( 'FlashMessenger' )
            ->clearCurrentMessages ();
    }

    $this->view->alert = $messages;
}

I want to make this into a Controller plugin.

UPDATE: I realized why I need this - I want to pass my flash messages in JSON when called by the JSON context. Unless the messages are added to the View object, I don't receive the messages.

I was able to get the messages into an array, but I don't know how to pass them to the view:

class Plugin_FlashMessenger extends Zend_Controller_Plugin_Abstract
{
    public function postDispatch($request)
    {
        $flashmessenger = Zend_Controller_Action_HelperBroker::getStaticHelper ( 'FlashMessenger' );

        $messages = $flashmessenger->getMessages ();
        if ( $flashmessenger->hasCurrentMessages () )
        {
            $messages = array_merge ( $messages, $flashmessenger->getCurrentMessages () );
            $flashmessenger->clearCurrentMessages ();
        }

        // THIS LINE IS WRONG. HOW DO I SEND $messages TO THE VIEW?
        $this->view->alert = $messages;
    }
}

Bonus question - is this the right way to accomplish this? Thanks!

3

There are 3 answers

1
sudol On

If you are just looking to get this functionality in all of your controllers, you can just extend the Zend_Controller_Action and make a new class containing your post dispatch code.

2
Tjorriemorrie On

I believe it's the wrong way to do it. The FlashMessenger is to have little notifications from one request to the next; available in the view.

Thus, the flashmessenger is already a controller action helper (for the above purpose) why do you want to build another helper on top of that? :)

So, your problem is actually getting the messages in the view. For that, there is already a view helper. From noumenal. It's awesome.

0
Sonny On

I found your post while searching for the same thing. Based on this thread, there are two simple ways to accomplish it.

One: If your view is initialized during bootstrap (resources.view[] = is in your application.ini), you can simply call this:

$view = Zend_Controller_Front::getInstance()
        ->getParam('bootstrap')
        ->getResource('view');

Two: If your view is not initialized during bootstrap:

$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
if (null === $viewRenderer->view) {
    $viewRenderer->initView();
}
$view = $viewRenderer->view;