在Code Igniter中加载多个数据库的便捷方法

时间:2011-02-07 03:59:05

标签: codeigniter database-connection

我已经将相应的配置数组添加到database.php并且它们可以工作,但是,我想要一种更简单的方法来访问不同的数据库。现在我必须在每个控制器方法中做这样的事情:

function index(){
    $BILLING = $this->load->database('billing', TRUE);
    $INVENTORY = $this->load->database('inventory', TRUE);

    $data['billing'] = $BILLING->get('stuff');
    $data['inventory'] = $INVENTORY->get('stuff');
}

我希望能够将前两行放在某种过滤器或pre_controller挂钩之前。

1 个答案:

答案 0 :(得分:8)

您只需在构造函数中全局加载数据库实例,然后它们就可用于所有控制器方法......

示例控制器

class Example extends CI_Controller {

    //declare them globally in your controller
    private $billing_db;
    private $inventory_db;

    function __construct() {
        parent::__construct();

        //Load them in the constructor
        $this->billing_db = $this->load->database('billing', TRUE);
        $this->inventory_db = $this->load->database('inventory', TRUE);
    }

    function index() {

        //Then use them in any controller like this
        $data['billing'] = $this->inventory_db->get('stuff');
        $data['inventory'] = $this->billing_db->get('stuff');

    }

}

如果跨多个控制器使用这些相同的数据库,您可以考虑扩展基本控制器以包含这些全局变量,并在MY_Controller.php

中将它们加载到基本控制器的构造函数中

示例MY_Controller.php

class DB_Controller extends CI_Controller {

    //declare them globally in your controller
    private $billing_db;
    private $inventory_db;

    function __construct() {
        parent::__construct();

        //Load them in the constructor
        $this->billing_db = $this->load->database('billing', TRUE);
        $this->inventory_db = $this->load->database('inventory', TRUE);
    }

}

然后你会像这样使用它......

class Example extends DB_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {

        //Then use them in any controller like this
        $data['billing'] = $this->inventory_db->get('stuff');
        $data['inventory'] = $this->billing_db->get('stuff');

    }

}