Present notifications in Zend Framework 2 with the Flash Messenger

This article introduces you to the Zend Framework 2 Flash Messenger for displaying notifications within your application.

In some of my old Zend 1 projects I wrote a notifications class that I stored in the registry that allowed me to add messages from any area of my application, and then output them to the view. When I went about creating similar functionality for a new Zend 2 project, I stumbled upon the Flash Messenger... 

What's the Zend 2 Flash Messenger?

The Zend 2 flash messenger is a default Zend plugin that allows you to add notifications you'd like to present to your users. Messages are stored in self-expiring sessions and can be added to different namespaces, such as 'error' or 'success'. By default a simple message goes into the 'default' namespace, you can also add custom ones if you need to. 

The main purpose of the flash messenger is to allow you to present notifications between page loads (e.g. you do a save, and then have to redirect your users back to a list). However this handy message wrapper can also be used for single page requests, and it's nice to have solutions that can manage both scenarios.

Coupled with the plugin is a view helper that allows you to extract and present the messages. Let's take a look at an example...

Adding notification messages

The addMessage method will add a message to the 'default' namespace:

$this->flashMessenger()->addMessage('Welcome!');

Additional messages will be stacked within this namespace. You can also add different message types such as success and errors, which go into their corresponding namespaces. Here's an example of adding the those three types inside a demo action for a controller:

public function demoAction()
{
        // General messages
        $this->flashMessenger()->addMessage('Welcome!');
        $this->flashMessenger()->addMessage('How are you?');

        // Something works
        $this->flashMessenger()->addSuccessMessage('Request successfully completed!');

        // Something fails
        $this->flashMessenger()->addErrorMessage('Request failed :(');


        return new ViewModel();
}

Retrieving and presenting notification messages

Now that the messages have been added to the flash messenger, we can retrieve them from the view file (phtml) like so:

echo $this->flashMessenger()->renderCurrent('error', array('alert', 'alert-danger'));
echo $this->flashMessenger()->renderCurrent('success', array('alert', 'alert-success'));
echo $this->flashMessenger()->renderCurrent('default', array('alert', 'alert-info'));
$this->view->flashMessenger()->getPluginFlashMessenger()->clearCurrentMessagesFromNamespace('default');
$this->view->flashMessenger()->getPluginFlashMessenger()->clearCurrentMessagesFromNamespace('success');
$this->view->flashMessenger()->getPluginFlashMessenger()->clearCurrentMessagesFromNamespace('error');

Notice how we reference the namespace in the first parameter, and how we've also added some classes to apply some styling to the notifications (using the twitter bootrap css classes). We've also cleared the flash messenger namespaces after outputting them, otherwise you may find these show again after a page load.

If you want to output these messages throughout your application, you could save yourself a few lines and make updating how alerts are presented later by putting this code into a helper:

<?php
namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

class NotificationsHelper extends AbstractHelper
{
    public function __invoke()
    {
        echo $this->view->flashMessenger()->render('error', array('alert', 'alert-danger'));
        echo $this->view->flashMessenger()->render('success', array('alert', 'alert-success'));
        echo $this->view->flashMessenger()->render('default', array('alert', 'alert-info'));
        $this->view->flashMessenger()->getPluginFlashMessenger()->clearCurrentMessagesFromNamespace('default');
        $this->view->flashMessenger()->getPluginFlashMessenger()->clearCurrentMessagesFromNamespace('success');
        $this->view->flashMessenger()->getPluginFlashMessenger()->clearCurrentMessagesFromNamespace('error');
    }
}

Don't forget to invoke your helper in the module.config.php file:

'view_helpers' => array(
        'invokables'=> array(
            'NotificationsHelper' => 'Application\View\Helper\NotificationsHelper'
        )
    ),

Now all you need to add at the top of your view files (or layout for global use) is the following:

$this->NotificationsHelper();

FlashMessenger Plugin Methods

Here's a comprehensive list of the other methods available to you in the flash messenger plugin:

  • setSessionManager - use a different session manager
  • getSessionManager - get registered session manager
  • getContainer - return the message container
  • setNamespace - define a specific namespace for storing messages
  • getNamespace - get current namespace for storing messages
  • addMessage - add a message to the current namespace
  • hasMessages - check if there are any messages in current namespace
  • getMessages - get messages in current namespace
  • clearMessages - wipe out current messages
  • hasCurrentMessages - were messages added in current request?
  • getCurrentMessages - get messages from current request
  • clearCurrentMessages - clear from current request
  • clearMessagesFromContainer - clear all messengers from current container
  • add*namespace*Message - add message to namespaces (info, warning, success, error)
  • hasCurrent*namespace*Message - check if namespace has messages

Flash Helper Methods

The view helper also has a few useful methods for manipulating how the messages are presented:

  • setMessageOpenFormat (e.g. '<div%s><p>')
  • setMessageSeparatorString (e.g. '</p><p>')
  • setMessageCloseString (e.g. '</p></div>');

Sign Up

NEXT: Unit Testing with Zend 2 and PHPUnit

In this article we'll be taking a look at how to integrate PHPUnit with Zend 2 and how to run some simple tests against services and controllers.

comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.