Created
October 17, 2011 14:45
-
-
Save nicholasruunu/1292765 to your computer and use it in GitHub Desktop.
Flash message error handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Message + Flash Message class | |
* | |
* Usage: $this->message->success('Your thing was successful', (bool) $is_flash, (string) $group); | |
* $this->message->error('There was an error'); | |
* | |
* @author Nicholas Ruunu | |
*/ | |
class Message { | |
private $CI; | |
private $types = array('success', 'error', 'warning', 'info'); | |
private $messages = array(); | |
private $flash_messages = array(); | |
function __construct() | |
{ | |
$this->CI =& get_instance(); | |
$this->CI->load->library('session'); | |
if($this->CI->session->flashdata('_messages') !== FALSE) | |
{ | |
$this->messages = (array) $this->CI->session->flashdata('_messages'); | |
} | |
} | |
/** | |
* Get all the $messages in an array | |
* | |
* @return array $messages | |
* @author Nicholas Ruunu | |
*/ | |
public function get_all() | |
{ | |
return $this->messages; | |
} | |
/** | |
* Get all messages in a specified $group | |
* | |
* @param string $group | |
* @return array $messages[$group] | |
* @author Nicholas Ruunu | |
*/ | |
public function get($group) | |
{ | |
$group = (string) $group; | |
return isset($this->messages[$group]) ? $this->messages[$group] : array(); | |
} | |
public function __call($name, $arguments) | |
{ | |
if(in_array($name, $this->types) && isset($arguments[0])) | |
{ | |
$message = (object) array( | |
'type' => $name, | |
'text' => (string) $arguments[0], | |
'is_flash' => isset($arguments[1]) ? (bool) $arguments[1] : TRUE, | |
'group' => isset($arguments[2]) ? (string) $group : FALSE | |
); | |
$this->_set_message($message); | |
} | |
} | |
private function _set_message($message) | |
{ | |
$message_object = (object) array('type' => $message->type, 'text' => $message->text); | |
$message_stack = &_get_message_stack($message->is_flash); | |
if($message->group !== FALSE) | |
{ | |
$message_stack[$message->group][] = $message_object; | |
} | |
else | |
{ | |
$message_stack[] = $message_object; | |
} | |
} | |
private function &_get_message_stack($is_flash = FALSE) | |
{ | |
return (bool) $is_flash ? $this->flash_messages : $this->messages; | |
} | |
function __destruct() | |
{ | |
if( ! empty($this->flash_messages)) | |
{ | |
$this->CI->session->set_flashdata('_messages', $this->flash_messages); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment