Wednesday, 25 December 2013

Implement Flash Messages using Session in PHP - Part1

As part of the post series, today we are going to see how we can implement Flash Messages using PHP Session. Before proceeding into that, first i  like to explain what is Flash Message and its usage.

What is Flash Message

Flash message is a message that will be shown/displayed only once. if you reload the browser or navigated to other pages and came back, you won't see the same message displayed again.

Its Usage: 
  • It is mainly used for displaying Error Messages, it may be form validation messages
  • It is also used for informing users about the success/failure of the execution. it may be database save confirmation message
  • This concept is used in all available PHP Frameworks like Zend Framework, Symphony and Yii etc.
Implementation:

In any server side programming langauge (PHP, Java), when you are implementing class using OOPS, please implement using Interface class. This helps code re-usablility, extending classes and Dependency Injection.

First, let see the implementation of the Interface class with name 'FlashMessageInterface'. Here is the implementation code

interface FlashMessageInterface {
    /**
     * get flash message from session by key
     * @param string $key
     * @param boolean $delete
     * @param mixed $defaultValue
     */

    public function getFlash($key, $delete = true, $defaultValue = null);

    /**
     * set flash message in session using key and value
     * @param string $key
     * @param mixed $value
     * @param mixed $defaultValue
     */

    public function setFlash($key, $value, $defaultValue = null);

    /**
     * get all the flash messages
     * @param boolean $delete
     */

    public function getFlashes($delete = true);

    /**
     * clear/unset all the flash messages in session
     */

    public function clearFlashes();

}

 This Interface class contains four public methods. we will see the implementation for this Interface class in Part 2.

Hope, you enjoyed this Post.

No comments:

Post a Comment