For the uninitiated in the dark art of Zend Framework, the flashMessenger action helper is a session based message system that allows you to store and retrieve messages while redirecting and forwarding to different pages. A quick browse through the source code reveals that the flash messenger does nothing more complicated than adding a few arrays to a session object. But yet, when set up properly it can be a great replacement for any custom messaging systems you use to provide feedback to your users on a site.
Like most Zend Framework components, the FlashMessenger needs a bit of tweaking before it’s ready to be part of your application. The main bit of tweaking we need to do involves the namespace. The messenger only has one namespace set at initialisation (default). More than often we will need a few namespaces for messaging. For instance you would often want to separate out error messages from success messages or notifications. This is where namespacing comes in. The following examples are contained in controller actions:
$this->_flashMessenger = $this->_helper
->getHelper('FlashMessenger');
if ($errrors) {
$this->_flashMessenger->setNamespace('error');
foreach ($errors as $errorItem) {
$this->_flashMessenger->addMessage($errorItem);
}
} else {
$this->_flashMessenger->setNamespace('success');
$this->_flashMessenger->addMessage('Success.');
}
$this->_flashMessenger->resetNamespace();
Once you have this set up you can retrieve messages from specific namespaces like so:
$this->_flashMessenger->setNamespace('error');
$this->view->errors = $this->_flashMessenger->getMessages();
$this->_flashMessenger->resetNamespace();
Always remember to reset the namespace after changing it or you might get confusing messages! Changing namespaces generates a lot of repeated code so it should really be moved into an messenger object of it’s own that will handle the namespace processing for you.
