[eluser]iConTM[/eluser]
Hello,
I made a class to easily manage messages.
What does it do:
- Register and fetch messages
- Ability to register messages under a certain category.
- Refer to a language file.
- Prefixes and suffixes for messages can be set for each category.
- Allows you to store messages in session.
Maybe this class is helpful for someone
any tips are welcome
greets
Code:
<?php
class Messages
{
protected $_ci = null;
protected $_messages = array();
protected $_template = array();
protected $_newline = "\n";
public $sess_key = 'messages';
public $auto_save = false;
public function __construct($params = array())
{
// parse params
if (count($params) > 0)
{
foreach ($params as $key => $value)
{
if (isset($this->$key) && strpos($key, '_') !== 0)
{
$this->$key = $value;
}
}
}
$this->_ci =& get_instance();
$this->_ci->load->library('session');
// do we have messages in session?
$sess_msg = $this->_ci->session->flashdata($this->sess_key);
if (is_array($sess_msg))
{
$this->_messages = $sess_msg;
}
// get default template
$this->_template = $this->_default_template();
}
public function get($cat = null, $prefix = '', $suffix = '')
{
# Are there messages? if not, we are done.
if (count($this->_messages) == 0)
{
return '';
}
$str = '';
foreach ($this->_messages as $msg)
{
// when category specified return all messages under that category.
// If not, return all messages.
$start = $prefix;
$end = $suffix;
if ($cat == null || $cat == $msg['cat'])
{
// when no prefix or suffix set, get it from template.
if ($start == '')
{
if (isset($this->_template[$msg['cat'].'_prefix']))
{
$start = $this->_template[$msg['cat'].'_prefix'];
}
else
{
$start = $this->_template['default_prefix'];
}
}
if ($end == '')
{
if (isset($this->_template[$msg['cat'].'_suffix']))
{
$end = $this->_template[$msg['cat'].'_suffix'];
}
else
{
$end = $this->_template['default_suffix'];
}
}
$str .= $start.$msg['text'].$end.$this->_newline;
}
}
return $str;
}
public function set($message, $cat = 'default', $save = null)
{
# create message
$msg = array();
$msg['cat'] = $cat;
$msg['text'] = $message;
$this->_messages[] = $msg;
if ($save == true || $save == null && $this->auto_save == true)
{
$this->save();
}
}
public function set_lang($key, $cat = 'default', $save = null)
{
$text = $this->_ci->lang->line($key);
if (!$text)
{
$text = 'Unable to find language key.';
}
$this->set($text, $cat, $save);
}
public function set_template($tpl)
{
if (count($tpl) > 0)
{
foreach ($tpl as $key => $value)
{
$this->_template[$key] = $value;
}
}
}
public function save()
{
$this->_ci->session->set_flashdata($this->sess_key, $this->_messages);
}
protected function _default_template()
{
return array(
'default_prefix' => '<p>',
'default_suffix' => '</p>'
);
}
}