如何通过扩展CodeIgniter中的CI_Controller来同时运行多个数据库?

时间:2018-02-05 03:16:50

标签: php codeigniter

我想自动加载我的多个数据库,以便我可以同时使用它们。我在/application/config/database.php

中有此配置
$active_group = 'identity';
$query_builder = TRUE;

// DB Connection
$__db['hostname'] = 'localhost';
$__db['username'] = 'root';
$__db['password'] = '1234';

// Database 1
$db['identity'] = array(
    'dsn'      => '',
    'dbdriver' => 'mysqli',
    'hostname' => $__db['hostname'],
    'username' => $__db['username'],
    'password' => $__db['password'],
    'database' => 'x1zn2j_identity',
    'dbprefix' => 'id_',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'cachedir' => '',
    'swap_pre' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'encrypt'  => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

// Database 2
$db['control'] = array(
    'dsn'      => '',
    'dbdriver' => 'mysqli',
    'hostname' => $__db['hostname'],
    'username' => $__db['username'],
    'password' => $__db['password'],
    'database' => 'x1eg2x_ctrl',
    'dbprefix' => 'ctrl_',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'cachedir' => '',
    'swap_pre' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'encrypt'  => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

现在为了使其更加灵活,因为将来我可能会添加一个新的数据库并将它们包含在我的database.php配置文件中,这样它就会成为一个无障碍的框架。所以我做的是创建了一个名为MultiDB.php的新库,并将其添加到autoload.php配置文件中,以便在每次加载页面时添加它。然后我添加这段代码:

class MultiDB
{
    public $dbase = array();

    function __construct()
    {
        global $db;

        foreach($db as $database)
        {
            $this->dbase[$database] = $this->load->database($database, TRUE);
        }
    }
}

显然,它不会起作用。我希望它根据$db配置自动加载数据库。因此,如果我要添加新的数据库配置,新数据库将加载并可以使用CI的查询生成器来使用。

任何?

1 个答案:

答案 0 :(得分:1)

基本上你想创建一个扩展MY_Controller的核心CI_Controller并加载不同的配置并将它们添加到public类变量中。这样,当您在application/controllers中创建包含视图的控​​制器时,您可以扩展MY_Controller而不是CI_Controller,从而可以访问MY_Controller的所有公共方法,包括数据库属性。

// application/core/MY_Controller.php
class MY_Controller extends CI_Controller {

    public $DB1, $DB2;

    public function __construct() {
        parent::__construct();
        $this->DB1 = $this->load->database('identity', TRUE);
        $this->DB2 = $this->load->database('control', TRUE);
    }

}

// application/controllers/Some_controller.php
// extend MY_Controller instead CI_Controller
class Some_controller extends MY_Controller {

    public function index() {

        $this->DB1->query(...) // query in database 1
        $this->DB2->query(...) // query in database 2
    }

}