zzmssw
Last Updated: February 25, 2016
·
5.477K
· rayfranco

Flashdata with ease in CodeIgniter

<?php

/**
* @author Franco Bouly 25/12/2010
* @version 0.1
* @name Flash - Flashdata with ease
*
*/


class Flash {

    var $CI;
    var $data = array();
    var $layout = '<div class="%s">%s</div>';

    var $_prefix = '_flash';

    function Flash() {
        $this->CI =& get_instance();
        $this->CI->load->library('session');
        $this->_local_store();
    }

    function get($format = TRUE, $keep = FALSE) {
        $data = unserialize($this->CI->session->userdata($this->_prefix));
        if ($keep === FALSE) {
            $this->CI->session->unset_userdata($this->_prefix);
        }

        if ($format === TRUE AND is_array($data) AND count($data) > 0) {
            $data_temp = '';
            foreach ($data as $d) {
                $data_temp .= sprintf($this->layout, $d['class'], $d['message']) . "\r\n";
            }
            $data = (string) $data_temp;
            unset($data_temp);
        }
        $this->_local_store();
        return $data;
    }

    function add($message, $class = 'error') {
        $this->_local_store();
        $store = array(
            'message' => $message,
            'class' => $class,
            'layout' => $this->layout,
        );
        $this->data[] = $store;
        $this->CI->session->set_userdata($this->_prefix,serialize($this->data));
    }

    function _local_store() {
        $this->data = unserialize($this->CI->session->userdata($this->_prefix));
    }

}

?>

I tought the Flashdata method of the CodeIgniter Session Library wasn't good enough for many of my project, so I set up this Library a way easier yet simple to use.

Because many cases of flashdata use is showing errors or validation messages (in my opinion), it should be tweaked this way. Just add a message like this :

$this->flash->add('Yay it works','valid');

and it will show up next time you call :

echo $this->flash->get();

something like this :

<div class="valid">Yay it works</div>

The point I needed the most is to queue multiple messages. So the method add just let you add as many "flashes" as you want. So

$this->flash->add('Yay it works','valid');
$this->flash->add('Yay it works, still','valid');

Will display 2 boxes.

You also can change the "layout" easily, by changing the layout parameter. You can do something like :

$this->flash->layout = '<div><span class="%s_icon"></span>%s</div>';

But keep it simple, as the first var will be the "class" parameter (second parameter in the add() method), and the second will be the message, if you need more flexibility, you'll have to hack the add() method yourself... Sorry about that.

Hope this helps, feel free to comment and add some functionnality on it's own pastebin : http://pastebin.com/Me1nNHxh

2 Responses
Add your response

17208

Useful class, Thank you :)

over 1 year ago ·
17490

Simple, classy, ultra useful.

over 1 year ago ·