Welcome Guest, Not a member yet? Register   Sign In
Where to define database when not autoloading?
#2

You could extend the loader and add 2 methods to connect to your databases (along with two properties in the super object to reference them). The easiest way to do so would be to create a "MY_Loader" class and copy the database() method from the CI loader into your loader, then refactor each copy to use unique method names and reference unique properties on the $CI instance. In other words, something like this:

PHP Code:
<?php 

class MY_Loader extends CI_Loader
{
    public function 
__construct()
    {
        
parent::__construct();
    }

    public function 
databaseOne($params ''$return FALSE$query_builder NULL)
    {
        
// Grab the super object
        
$CI =& get_instance();

        
// Do we even need to load the database class?
        
if ($return === FALSE && $query_builder === NULL && isset($CI->db1) && is_object($CI->db1) && ! empty($CI->db1->conn_id))
        {
            return 
FALSE;
        }

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

        if (
$return === TRUE)
        {
            return 
DB($params$query_builder);
        }

        
// Initialize the db variable. Needed to prevent
        // reference errors with some configurations
        
$CI->db1 '';

        
// Load the DB class
        
$CI->db1 =& DB($params$query_builder);
        return 
$this;
    }

    public function 
databaseTwo($params ''$return FALSE$query_builder NULL)
    {
        
// Grab the super object
        
$CI =& get_instance();

        
// Do we even need to load the database class?
        
if ($return === FALSE && $query_builder === NULL && isset($CI->db2) && is_object($CI->db2) && ! empty($CI->db2->conn_id))
        {
            return 
FALSE;
        }

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

        if (
$return === TRUE)
        {
            return 
DB($params$query_builder);
        }

        
// Initialize the db variable. Needed to prevent
        // reference errors with some configurations
        
$CI->db2 '';

        
// Load the DB class
        
$CI->db2 =& DB($params$query_builder);
        return 
$this;
    }


Then you would use it like this:

PHP Code:
$this->load->databaseOne();
$this->db1->query($sql1);

$this->load->databaseTwo();
$this->db2->query($sql2); 

The loader would then manage the connection(s), returning the open connection if it already exists.

With some extra work, it's probably possible to do this with less code, but this is the easiest/simplest solution that came to mind.
Reply


Messages In This Thread
RE: Where to define database when not autoloading? - by mwhitney - 04-29-2016, 12:43 PM



Theme © iAndrew 2016 - Forum software by © MyBB