Skip to content

Extending Database Drivers

World Wide Web Server edited this page Jul 4, 2012 · 31 revisions

Much complaints abotu not being able to extend the database class DB. In the docs it says this can't be done, but here is a simple solution that fits it all! Don't believe it, well read on..

The solution comes in 3 simple steps:

  1. If you haven't already extended your loader class, you do so by creating the file MY_Loader.php into your libraries directory in the application path. It's content is at first:

[code] <?php

class MY_Loader extends CI_Loader {

}

?> [/code]

  1. You add the following function to your MY_Loader class:

[code] /** * Database Loader * * @access public * @param string the DB credentials * @param bool whether to return the DB object * @param bool whether to enable active record (this allows us to override the config setting) * @return object */ function database($params = '', $return = FALSE, $active_record = FALSE) { // Do we even need to load the database class? if (class_exists('CI_DB') AND $return == FALSE AND $active_record == FALSE) { return FALSE; }

        require_once(BASEPATH.'database/DB'.EXT);

        // Load the DB class
        $db =& DB($params, $active_record);

        $my_driver = config_item('subclass_prefix').'DB_'.$db->dbdriver.'_driver';
        $my_driver_file = APPPATH.'libraries/'.$my_driver.EXT;

        if (file_exists($my_driver_file))
        {
            require_once($my_driver_file);
            $db =& new $my_driver(get_object_vars($db));
        }

        if ($return === TRUE)
        {
            return $db;
        }
        // Grab the super object
        $CI =& get_instance();

        // Initialize the db variable.  Needed to prevent
        // reference errors with some configurations
        $CI->db = '';
        $CI->db = $db;
    // Assign the DB object to any existing models
    $this->_ci_assign_to_models();
}

[/code]

  1. Now you are ready to create your Database driver extension class, that you name depending on which driver (available: mysql, prostgres, ..) you use. You put it also in your applications libraries directory, naming it accordingly MY_DB_mysql_driver.php (again substitute the mysql part for whatever is accurate):

[code] <?php

class MY_DB_mysql_driver extends CI_DB_mysql_driver {

function __construct($params){ parent::__construct($params); log_message('debug', 'Extended DB driver class instantiated!'); }

function idonothing(){ return $this; }

} ?> [/code]

Hey you are done! Congrats, now you can use the following, where idonothing() is the sample function from above, that just does nothing else than pass on your db object. [code] $this->db->from('sometable')->idonothing()->limit(1)->get(); [/code]

Category:Databases

Clone this wiki locally