1. 程式人生 > >phalcon 連線多個數據庫 phalcon multi-database

phalcon 連線多個數據庫 phalcon multi-database

http://stackoverflow.com/questions/22197678/how-to-connect-multiple-database-in-phalcon-framework

//This service returns a MySQL database
$di->set('dbMaster', function() {
     return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "",
        "password" => "",
        "dbname" => ""
    ));
});

//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
     return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "",
        "password" => "",
        "dbname" => ""
    ));
});

public function initialize()
{
    $this->setConnectionService('dbMaster');
    //or
    $this->setConnectionService('dbSlave');
}
這是給出來的案例,在實際程式碼環境,用的是預設生成的模板檔案。

修改配置檔案

    'database' => array(
        'adapter'     => 'Mysql',
        'host'        => '127.0.0.1',
        'username'    => 'root',
        'password'    => 'toor',
        'dbname'      => 'db1',
        'charset'     => 'utf8',
    ),
    'db2' => array(
        'adapter'     => 'Mysql',
        'host'        => '127.0.0.1',
        'username'    => 'root',
        'password'    => 'toor',
        'dbname'      => 'db2',
        'charset'     => 'utf8',
    ),

$di->set('db', function () use ($config) {
    return new DbAdapter($config->database->toArray());
});
$di->set('db2', function () use ($config) {
    return new DbAdapter($config->db2->toArray());

在model中使用時,
class user  extends Model
{
    public function initialize()
    {
        $this->setConnectionService('db2');
    }
}