Quick Hack to use Multiple DBs with MY_Model

UPDATE: Since writing this tutorial, I pushed this to Jamie's MY_Model repo and he has accepted it. You will find it already included in the latest version.

A current project requires me to switch back and forth between two databases. Here's a quick snippet of how to do that when you have a parent MY_Model class. I use Jamie Rumbelow's MY_Model, found here: http://github.com/jamierumbelow/codeigniter-base-model The code is quite simple, and works similarly to the exisiting table-loading function. First, set up a variable at the top:
protected $_db;
Now, we'll create a database loading function:
    private function _set_database()
    {
        //we'll read the config file later
        if ($this->_db == null )
        {
            $this->db = $this->load->database('default', TRUE);
        }    
        else
        {
            $this->db = $this->load->database($this->_db, TRUE);
        }
    }
In our __construct function, we'll call it:
$this->_set_database();
So, that's it for the MY_Model changes. Simple, wasn't it? Now, in each model where we want to use a different db from the default, we say:
class Project_model extends MY_Model
{
    public function __construct()
    {       
        $this->_db = 'catalog';
        parent::__construct();
    }

}
Notice we set it BEFORE the call to parent. That's it. There ain't no more. Pretty simple, enso?

Contact me