Требуется автозагрузка базы данных, префикса расширений классов MY.
item если не находит элемент конфигурации в загруженном массиве обращается в БД и ищет там значение данного элемента, если не находит возвращает FALSE.
get_item возвращает элемент с базы в виде массива
get_list возвращает полный список констант со всеми их параметрами
save_item сохраняет параметр в базу данных
- Код: Выделить всё
class MY_Config extends CI_Config {
var $db = null;
function MY_Config()
{
parent::CI_Config();
log_message('debug', "Extends Config Class Initialized");
}
/**
* Obtaining a database object and run a autoload
*
*
* @access private
* @param string $item Vernet value of the item if it will be processed in autoload
* @return <type>
*/
function init_db($item=null) {
$return = null;
if($this->db !== null)
return $return;
$CI =& get_instance();
$this->db = $CI->db;
/* При вызове контроллера еще не запущено ядро CI,
* потому автолоадер запускаем при первой попытке получить данные из базы
*/
if(!$this->item('autoload_db_config')) {
log_message('debug', "Autoload Config OFF");
return $return;
}
$this->init_db();
$this->db->select('config_name, config_value');
$this->db->where('autoload', 'yes');
$r = $this->db->get('config');
if($r->num_rows == 0)
return $return;
$datatable = $r->result_array();
foreach ($datatable as $row)
{
$this->set_item($row['config_name'], unserialize($row['config_value']));
if($item !== null && $item==$row['config_name'])
$return = unserialize($row['config_value']);
}
return $return;
}
/**
* Fetch a config file item
*
*
* @access public
* @param string the config item name
* @param string the index name
* @param bool used database
* @return string
*/
function item($item, $index = '', $use_db=true)
{
if(($pref = parent::item($item, $index)) !== FALSE || $index != '' || $use_db != true)
return $pref;
if ( isset($this->config[$item]))
return FALSE;
/**
* Если значение будет найденно при автозагрузке то мы
* его сразуже вернем
*/
if(($pref = $this->init_db($item)) !== null )
return $pref;
$this->db->where('config_name', $item);
$r = $this->db->get('config', 1);
if($r->num_rows == 0)
return false;
$data = $r->row_array();
$pref = unserialize($data['config_value']);
$this->set_item($item, $pref);
return $pref;
}
/**
* Get config item
*
* Gets the item from the database as an array
*
* @access public
* @param string $item
* @return array
*/
function get_item($item)
{
$this->init_db();
$this->db->where('config_name', $item);
$r = $this->db->get('config', 1);
if($r->num_rows == 0)
return false;
$datarow = $r->row_array();
$datarow['config_value'] = unserialize($datarow['config_value']);
return $datarow;
}
/**
* Get list const items
*
*
* @access public
* @return array
*/
function get_list() {
$this->init_db();
$r = $this->db->get('config');
if($r->num_rows == 0)
return false;
$datatable = $r->result_array();
$func = create_function('$v', '$v[\'config_value\'] = unserialize($v[\'config_value\']); return $v;');
$datatable = array_map($func, $datatable);
return $datatable;
}
/**
* Save to db config
*
*
* @param string $item
* @param string $value
* @param string $title
* @param string $description
* @param string $autoload yes/no
*/
function save_item($item, $value, $title='', $description='', $autoload = 'no')
{
$this->init_db();
$this->db->where('config_name', $item);
$r = $this->db->get('config', 1);
if($autoload != 'yes' && $autoload != 'no')
$autoload = 'no';
if($r->num_rows == 0)
$this->db->insert('config', array('config_name'=>$item, 'config_value'=>serialize($value), 'config_title'=>$title, 'config_description'=>$description, 'autoload'=>$autoload));
else
{
$this->db->where('config_name', $item);
$this->db->update('config', array('config_value'=>serialize($value), 'config_title'=>$title, 'config_description'=>$description, 'autoload'=>$autoload));
}
$this->set_item($item, $value);
}
}
- Код: Выделить всё
CREATE TABLE `config` (
`config_title` varchar(255) default NULL,
`config_name` varchar(255) NOT NULL default '',
`config_value` blob,
`config_description` text,
`autoload` varchar(20) NOT NULL default 'no',
PRIMARY KEY (`config_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
По большей части интересует критика
- Код: Выделить всё
changelog
1. Добавлена возможность хранить любые данные которые можно сериализовать
