Welcome Guest, Not a member yet? Register   Sign In
Database based Config library
#1

[eluser]steelaz[/eluser]
A while ago codearachnid posted his extension to CI base Config library to add config items from database table - wiki. I made some modification and been using it for most of my projects.

Since CI Config library is loaded automagically, there's no need to load it explicitly. To start using it, add this line in your controller (constructor is a good place):

Code:
$this->config->load_db_items();

load_db_items() method will check if "settings" table exists and create it if necessary. Then it will read all key => value pairs in the table and add them to Config object. After load_db_items() was called, you can access you database values just like regular items, i.e.:

Code:
$website_name = $this->config->item('website_name');

To add or update database item use save_db_item() method, i.e.:

Code:
$this->config->save_db_item('website_name', 'My Website');

To remove database item use remove_db_item() method, i.e.:

Code:
$this->config->remove_db_item('website_name');


To install, create /application/libraries/MY_Config.php and copy/paste the code below. Change table name if you want to.
Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
* CodeIgniter Config Extended Library
*
* This class extends the config to a database. Based on class written by Tim Wood (aka codearachnid).
*
* @package       CodeIgniter
* @subpackage    Extended Libraries
* @author        Arnas Lukosevicius (aka steelaz)
* @link          http://www.arnas.net/blog/
*
*/

class MY_Config extends CI_Config
{
    /**
     * CodeIgniter instance
     *
     * @var object
     */
    private $CI = NULL;

    /**
     * Database table name
     *
     * @var string
     */
    private $table = 'settings';


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Load config items from database
     *
     * @return void
     */
    public function load_db_items()
    {
        if (is_null($this->CI)) $this->CI = get_instance();

        if (!$this->CI->db->table_exists($this->table))
        {
           $this->create_table();
        }

        $query = $this->CI->db->get($this->table);

        foreach ($query->result() as $row)
        {
            $this->set_item($row->key, $row->value);
        }

    }

    /**
     * Save config item to database
     *
     * @return bool
     * @param string $key
     * @param string $value
     */
    public function save_db_item($key, $value)
    {
        if (is_null($this->CI)) $this->CI = get_instance();

        $where = array('key' => $key);
        $found = $this->CI->db->get_where($this->table, $where, 1);

        if ($found->num_rows > 0)
        {
            return $this->CI->db->update($this->table, array('value' => $value), $where);
        }
        else
        {
            return $this->CI->db->insert($this->table, array('key' => $key, 'value' => $value));
        }
    }

    /**
     * Remove config item from database
     *
     * @return bool
     * @param string $key
     */
    public function remove_db_item($key)
    {
        if (is_null($this->CI)) $this->CI = get_instance();

        return $this->CI->db->delete($this->table, array('key' => $key));
    }

    /**
     * Create database table (using "IF NOT EXISTS")
     *
     * @return void
     */
    public function create_table()
    {
        if (is_null($this->CI)) $this->CI = get_instance();

        $this->CI->load->dbforge();

        $this->CI->dbforge->add_field("`id` int(11) NOT NULL auto_increment");
        $this->CI->dbforge->add_field("`updated` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP");
        $this->CI->dbforge->add_field("`key` varchar(255) NOT NULL");
        $this->CI->dbforge->add_field("`value` text NOT NULL");

        $this->CI->dbforge->add_key('id', TRUE);

        $this->CI->dbforge->create_table($this->table, TRUE);
    }
}

/* End of file MY_Config.php */
/* Location: ./application/libraries/MY_Config.php */
#2

[eluser]tdktank59[/eluser]
While the methodology looks great!
A few quirks I see.

First why set the instance in every single method move all that stuff up to the constructor that's what its there for.

otherwise love the ideas.
#3

[eluser]steelaz[/eluser]
I tried that, but it would throw an error: "Call to undefined function get_instance()". I assume it's because CI Config library is loaded before get_instance() is available.
#4

[eluser]tdktank59[/eluser]
Fair enough, im working extending this to incorporate multiple config tables and make it behave closer to the original config class.
#5

[eluser]Phil Sturgeon[/eluser]
This is why I keep Config and "Settings" separate. They are logically different things and combining them gets messy.

By renaming to $this->settings you can use item() and set_item() just like the Config library, instead of using names like save_db_item() which to me looks dirty.

Good coding though. :-)
#6

[eluser]tdktank59[/eluser]
Well Phill while I agree on some point there...

Config is basically settings so logically they are pretty similar...
The config can only have so many settings...
#7

[eluser]steelaz[/eluser]
Well, the line between Config and Settings sometimes gets blurry, so I think it's a matter of preference or project you're working on. I extended my Config class when I wanted to move some hard-coded 3rd party config values to database and it worked out quite nicely.

I agree with "messy" factor, but I only use save_db_item() in my applications' "Settings" page. For the most part I call load_db_items() once in extended controller and it's $this->config->item() from there.
#8

[eluser]Phil Sturgeon[/eluser]
You are right steelaz, it's probably just down to preference but as I see it Config is core system configuration, only changeable by people who know what they are doing, and Settings are "here are your options, change as much as you like!" options handled through an GUI by the BDUs.

As they are different in my head and need to be loaded at different points in the application flow, it made more sense to be to keep them in separate libraries too.

Your approach is neater with load_db_items() and item() but it still seems like two cousins getting married to me.
#9

[eluser]tdktank59[/eluser]
After looking into this.

The 2 are almost impossible to marry together...
The database class was not made to load with the config class...

Looks like this will become a separate library that behaves similar and loads at the proper time to use the libraries...
#10

[eluser]Phil Sturgeon[/eluser]
Tongue




Theme © iAndrew 2016 - Forum software by © MyBB