0

I've this project where a different database should be used based on the current user. I'm using codeigniter with the Datamapper extension.

Ideal would be to set a different connection group in a controller which I can use in my datamapper models like:

var $db_params = 'user_specific';

However unlike the config params, the database params don't seem to be accessible from inside a controller. I did find a way where you needed to pass a variable ($db) when creating a new datamapper object in an answer to this question.

$customers = new customer(NULL, $db);
// The NULL I would need becuase the constructor expects an ID or nothing by default

However, most models would use the dynamic settings so it is a lot of work adding the $db variable everywhere... Is there any other solution so I can just do

$customer = new customer();

// And in my model use the dynamic 'config' settings like
var $db_params = 'user_specific';

It would be a great help. Thanks in advance.

Community
  • 1
  • 1
Brainfeeder
  • 2,604
  • 2
  • 19
  • 37

1 Answers1

0

Update:

An even simpler way would it be to connect to the database when you already retrieved the connection group you want to connect to. In your controller use:

class SomeController extends MY_Controller{

    public function index(){

        $connection_group = getCustomerConnectionGroup(); //example only
        $this->load->database($connection_group);

    }

}

While you cannot change the connection group during runtime, work it around by returning the connection ID and store it into a class property of MY_Controller

<?php

class MY_Controller extends CI_Controller{

    protected $mydb;

    public function __construct()
    {
        parent::__construct();
        $this->connect_to('default');
    }

    public function connect_to($group)
    {
        $this->mydb = $this->load->database($group, true);
    }

}

?>

Now in your normal Controllers you will be using the following

class SomeController extends MY_Controller{

    public function index(){

        $connection_group = getCustomerConnectionGroup(); //example only
        $this->connect_to($connectionGroup);

    }

}

Note that by doing this you need to use

$this->mydb->method();

troughout your application.

thpl
  • 5,810
  • 3
  • 29
  • 43
  • I see where you are going with this, but since I'm using the Datamapper ORM I don't need to connect to the database in my controller(s). The models take care of this. – Brainfeeder May 22 '13 at 09:53