MR.ASONG

Phalcon 框架如何实现主从读写分离

2016/08/26 746 0

假设你已经在 DI 容器里注册了俩 db services,如下:

<?php
// 主库
$di->setShared('dbWrite', function() use ($config) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => $config->w_database->host,
        "username" => $config->w_database->username,
        "password" => $config->w_database->password,
        "dbname" => $config->w_database->name
    ));
});
// 从库
$di->setShared('dbRead', function() use ($config) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => $config->r_database->host,
        "username" => $config->r_database->username,
        "password" => $config->r_database->password,
        "dbname" =>  $config->r_database->name
    ));
});

然后创建一个父 Model

<?php 
class BaseModel extends \Phalcon\Mvc\Model{

    public function initialize() {
        $this->setWriteConnectionService('dbWrite');
        $this->setReadConnectionService('dbRead');
    }

}

在子 Model 中直接继承即可:

<?php
class User extends BaseModel {
    //code here
}

添加新评论