Aug24th

Setting up flash messages in Zend Framework

This article is part of my Learning Zend Framework series.

It took me a few hours of reading and fiddling with the code to get my flash messages working with Zend Framework so I thought I could help you out by “putting it all together.”

In this example, I’m using Zend_Layout but you could put your flash messages in a view just as easy. My intent for this functionality is to allow the application to call a method that would set a flash message and then redirect the user to another page and display the flash messages. This is much like built in functionality of the Ruby On Rails or CakePHP flash messenger mechanism.

in my bootstrap file (this is not necessary if you are not using layouts):

// setup the "layouts" of MVC
Zend_Layout::startMvc(array(
		'layoutPath'=>'../application/views/layouts',
		'layout'=>'main'
));

I chose to create a custom controller that my other action controllers would extend. This also serves as a central place to add my messaging and redirecting.

MyController.php

class MyController extends Zend_Controller_Action
{
	protected $_redirector;
	protected $_flashMessenger;

	public function init()
	{
		$this->_flashMessenger 	= $this->_helper->getHelper('FlashMessenger');
		$this->_redirector = $this->_helper->getHelper('Redirector');
	}

	protected function flash($message,$to)
	{
		$this->_flashMessenger->addMessage($message);
		$this->_redirector->gotoUrl($to);
	}

	protected function setMessages()
	{
		$this->view->messages = join("“,$this->_flashMessenger->getMessages());
	}
    public function postDispatch()
	{
		$this->setMessages();
		parent::postDispatch();
	}

}

In the above file, you will notice 4 methods. The init() method initializes the flashMessenger and Redirector helpers. The flash() method is the method your controllers should actually call. This will set the flash message and then redirect to a url. I made this method very simple but you could easily allow it to take in a standard set of parameters for the controller/action and params. The setMessages() method is used to set the flash messages to a variable accessible by your view/layout. The postDispatch() method is called after your action is complete, so I’m using this method to set the flash messages in the view.

In your controller action:

public function login()
{
    // do some login stuff here
    if($logged_in) {
        $this->flash('You are now logged in','/dashboard'); // this will set the message and redirect
    }
}

And in your view/layout:

echo $this->messages;

It’s as simple as that.

If you hunt through all of the Zend Framework documentation, you will eventually get here (with trial and error). But, like I said, it took me a while to find a working solution so I thought I would share.