2013-05-22 33 views
0

我有這個項目,根據當前用戶應該使用不同的數據庫。 我在Datamapper擴展中使用codeigniter。基於當前用戶動態設置數據庫

理想的做法是設置不同的連接組中的控制器,我可以在我的DataMapper機型使用,如:

var $db_params = 'user_specific'; 

然而不同的是配置參數,可以在數據庫PARAMS似乎還沒有從訪問在控制器內部。 我確實找到了一種方法,當您在this問題的答案中創建新的datamapper對象時,您需要傳遞一個變量($ db)。

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

然而,所以它是一個大量的工作將無處不在$ DB變量的大部分車型將使用動態設置... 是否有任何其他的解決方案,所以我可以做

$customer = new customer(); 

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

這將是一個很大的幫助。提前致謝。

回答

0

更新:

一個更簡單的方式會是連接到數據庫時,你已經檢索到您想要連接到連接組。在你的控制器使用方法:

class SomeController extends MY_Controller{ 

    public function index(){ 

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

    } 

} 

雖然你不能在運行時更改連接組,通過返回連接ID各地工作,並在你的正常存儲到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); 
    } 

} 

?> 

現在您將使用控制器下

class SomeController extends MY_Controller{ 

    public function index(){ 

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

    } 

} 

注意,通過這樣做,你需要使用

$ this-> mydb-> method();

整個應用程序。

+0

我看到你要去哪裏,但由於我使用Datamapper ORM,因此我不需要連接到控制器中的數據庫。模型照顧這個。 – Brainfeeder