我有这个项目,其中应该根据当前用户使用不同的数据库。我使用codeigniter与Datamapper扩展。
理想的是在控制器中设置一个不同的连接组,我可以在我的数据映射器模型中使用,如:
var $db_params = 'user_specific';
然而,与配置参数不同的是,数据库参数似乎不能从控制器内部访问。我确实找到了一种方法,在这个问题的答案中创建一个新的数据映射器对象时,需要传递一个变量($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';
这将是一个很大的帮助。
更新:
一种更简单的方法是,当您已经检索到要连接的连接组时再连接到数据库。在控制器中使用:
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>()方法;