Using FlashMessenger

The Zend Framework offers us a scratchpad of sorts for passing messages to and from different controllers/actions. It is implemented as an action helper. It can be accessed by follows:

$flash = $this->_helper->getHelper(‘FlashMessenger’);

OR

$flash = $this->_helper->FlashMessenger;

Presented below is a structured approach to using FlashMessenger as an efficient “status message reporting system” on the beginning section of each page.

I invariably use a Base controller class which ALL my other action controllers extend. I find this to be an extremely slick way to enforce structure and reduce complexity. Moreover, it is recommended OOP.

Presenting basecontroller.php:

<?php

class BaseController extends Zend_Controller_Action {

    protected $db;
    protected $auth;
    protected $messenger;
    protected $logger;
    public function init()
    {
        $this->db=Zend_Db_Table::getDefaultAdapter();
        $this->view->baseUrl=Zend_Controller_Front::getInstance()->getBaseUrl();
        $this->auth=Zend_Auth::getInstance();
        $this->logger=Zend_Registry::get(‘logger’);
        $this->logger->setEventItem(‘username’, $this->auth->getIdentity());
       $this->messenger=$this->_helper->FlashMessenger;       
    }
   public function postDispatch()
    {
        $this->view->messages = $this->messenger->getCurrentMessages();
    }
}

?>

The sections used to initialize and use the flashmessenger object are indicated in bold.

In the init() function, a reference to the flashmessenger object is retrieved and assigned to the $messenger variable. By virtue of this being the base class, all the inherited classes now have access to this variable using $this->messenger.

When an action completes or when there is an event occurrence that you want displayed to the user, you can simply add that message onto the flashmessenger object like so:

$this->messenger->addMessage(‘Authentication Failed’);

Very Very Important : The getCurrentMessages() function on the messenger object is invoked in the postDispatch() method of the action controller. This is because you want the action method to execute, add the required messages onto the FlashMessenger and THEN display the messages when the view is displayed… got it? Gathering messages in the preDispatch() loop will not work as expected!

Once again, I cannot emphasize enough that understanding the Zend Framework flow is key to proper implementation.

Here is my loginAction script (in AuthController class)

class AuthController extends BaseController 
{

……

……

public function loginAction()
    {
        $request = $this->getRequest();
        if ($request->isPost())
        {
                $result = $this->auth->authenticate($authAdapter);
                if ($result->isValid())
                {
                    //Authenticated successfully
                    //Do what needs to be done
                    $this->_redirect($redirect);
                }
                else
                {
                    $this->messenger->addMessage(‘Login Failed..’);
                }
        }
        //Fall through and display the login.phtml page
    }

}

So, after loginAction() is executed, if the user supplied credentials are incorrect, the messenger contains the message “Login Failed..”

Ok.. onto the next step.. the Layout file. If you are not using Zend_Layout in your MVC app, you are missing a BIG service provided by the framework.. I strongly urge you to adapt a layout file.. It will make your apps so much easier. Also, it is trivial really to incorporate it in your project.

We will process ALL our messages in the layout so that messaging within the app becomes completely automated.. If you want to raise a message in any action, go ahead and use $this->messenger->addMessage() and when the view is displayed, messages are automatically displayed to the user.

Layout.phtml:

<div id=”mainContainer”>
<div id=”content”>
<h2 id=”secHeader” title=”Template Title”><span></span>Template Image</h2>
<ul>
<?php
foreach($this->messages as $msg)
{
    echo “<li>$msg</li>”;
}
?>
</ul>
<?php echo $this->layout()->content ?>

</div>
</div>

Our postDispatch() process copies all current messages onto a messages array in the view.. so simply iterate over that collection and display as a list (as there may be multiple messages)

That’s all there to it! Please feel free to drop me a line if you have any questions.

Advertisements

2 thoughts on “Using FlashMessenger

  1. Hey,

    Nice article! Exactly what I needed. I’m trying to learn ZF and this helps a lot, but I’ve still got one problem…

    "Fatal error: Class 'BaseController' not found"

    I do understand that I need to add something like a autoloader… But how?

    Regards Marc

    1. Hi Marc,

      Here’s how you can implement autoloading of classes (in recent versions of Zend framework)

      1. Create a folder (say ‘ZF’) in the ‘library’ folder

      2. Move basecontroller.php into the ZF subfolder and define it as
      class ZF_BaseController extends Zend_Controller_Action {…}

      3. Add the following line to your application.ini:
      autoloadernamespaces[]=”ZF”
      (this line automatically loads any classes prefixed with ‘ZF’ in the include path.. and the library folder is defined to be in the php include path in index.php)

      4. Make your controllers extend ZF_BaseController instead of basecontroller.. like so:
      class myController extends ZF_BaseController { .. }

      Hope this helps!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s