Which is the best way to display 'flash messages' in kohana v3?

后端 未结 5 1692
逝去的感伤
逝去的感伤 2021-02-04 13:52

I would like to know the best way to display flash messages in Kohana v3?

Some tutorials or examples would be helpful.

5条回答
  •  天命终不由人
    2021-02-04 14:24

    I've written a really simple class for this once. Check it out below. Usage examples below

    class Notice {
        private static $session;
        private static $initialized = false;
    
        // current notices
        private static $notices = array();
    
        function __construct() {
        }
    
        static function init() {
            self::$session = Session::instance();
            self::$notices['current'] = json_decode(self::$session->get_once('flash'));
            if(!is_array(self::$notices['current'])) self::$notices['current'] = array();
            self::$initialized = true;
        }
    
        static function add($notice, $key=null) {
            if(!self::$initialized) self::init();
            if(!is_null($key)) {
                self::$notices['new'][$key] = $notice;
            } else {
                self::$notices['new'][] = $notice;
            }
            self::$session->set('flash', json_encode(self::$notices['new']));
            return true;
        }
    
        static function get($item = null) {
            if(!self::$initialized) self::init();
            if($item == null) {
                return self::$notices['current'];
            }
            if(!array_key_exists($item, self::$notices['current']))
                    return null;
            return self::$notices['current'][$item];
        }
    }
    

    Examples (provided this class is saved as APPPATH . 'classes/notice.php'):

    Notice::add('Something great has happened!');
    Notice::add('Exciting! I\'ve got something to tell you!', 'message');
    
    echo Notice::get('message'); // "Exciting! I've got ..."
    foreach(Notice::get() as $message) {
       echo $i++ . $message .'
    '; }

    EDIT: funny... for some reason this question popped up somewhere, didn't notice it was a really old one... sorry for that!

提交回复
热议问题