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

 1<?php
 2// 主库
 3$di->setShared('dbWrite', function() use ($config) {
 4    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
 5        "host" => $config->w_database->host,
 6        "username" => $config->w_database->username,
 7        "password" => $config->w_database->password,
 8        "dbname" => $config->w_database->name
 9    ));
10});
11// 从库
12$di->setShared('dbRead', function() use ($config) {
13    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
14        "host" => $config->r_database->host,
15        "username" => $config->r_database->username,
16        "password" => $config->r_database->password,
17        "dbname" =>  $config->r_database->name
18    ));
19});

然后创建一个父 Model

1<?php
2class BaseModel extends \Phalcon\Mvc\Model{
3
4    public function initialize() {
5        $this->setWriteConnectionService('dbWrite');
6        $this->setReadConnectionService('dbRead');
7    }
8
9}

在子 Model 中直接继承即可:

1<?php
2class User extends BaseModel {
3    //code here
4}