[eluser]Mark LaDoux[/eluser]
After much experimentation, I've written a nice settings class that will pull settings from a database rather than from static files like the config class does in CodeIgniter. I had considered integrating it directly into the config class as a modification, but I wanted to a basic version where I didn't have to worry about overwriting static CodeIgniter config items. Anyway, here it is -->
// added missing semicolon
// made some syntax compatibility corrections thanks to InsiteFX
Code:
<?php
/**
* Setting Class
*
* class accesses application settings from a database.
*/
class setting
{
private $ci = null; // holds our CodeIgniter instance
private $items = null; // holds an array of our configuration items
private $table = null; // table to pull settings from
/**
* __cosntruct
*
* ensures that class is ready for proper function
*
* @access public
* @return void method does not return a result
*/
function __construct()
{
// get CodeIgniter instance
if( $this->ci === null )
{
$this->ci =& get_instance();
$this->ci->config->load('settings'); // let us autoload the settings
$this->table = $this->ci->config->item('settings_table');
}
if( $this->items === null )
{
$this->_refresh_items();
}
}
/**
* _refresh_items
*
* refreshes the item array
*
* @access private
* @return void method does not return a result
*/
private function _refresh_items()
{
$query = $this->ci->db->get($this->table);
$this->items = array();
if( $query->num_rows() > 0 )
{
while($row = $query->fetch_assoc())
{
$item = $row['item'];
$value = $row['value'];
// do some nice filtering
if(strtolower($value) == '{{false}}') $value = false;
if(strtolower($value) == '{{true}}') $value = true;
if(strtolower($value) == '{{null}}') $value = null;
if(strtolower($value) == '{{empty}}') $value = '';
$this->items[$item] = $value;
}
}
}
/**
* set
*
* sets the value of an item in the database
*
* @access public
* @param string $item item to set
* @param string $value value of the item
* @return void method does not return a result
*/
public function set($item, $value)
{
// do a little pre-filtering
if($value === false) $value = '{{false}}';
if($value === true) $value = '{{true}}';
if($value === null) $value = '{{null}}';
if($value == '') $value = '{{empty}}';
// quick test
if(isset($this->items[$item]))
{
$this->ci->db->where('item', $item);
$this->ci->db->update($this->table, array('value' => $value));
}
else
{
$this->ci->db->insert($this->table, array('item' => $item, 'value' => $value));
}
$this->_refresh_items();
}
/**
* get
*
* retrieves a setting from the database
*
* @access public
* @param string $item item to retrieve
* @return mixed value of the item if is set, else false
*/
public function get($item) {
if( isset($this->items[$item])) return $this->items[$item];
return false;
}
}