Phalcon连接多个数据库的时候需要配置多个连接
'tutorial' => [ //'adapter' => 'mysql', 'host' => '127.0.0.1', 'port' => '3306', 'username' => 'root', 'password' => '', 'dbname' => 'tutorial' ], 'invo' => [ //'adapter' => 'mysql', 'host' => '127.0.0.1', 'port' => '3306', 'username' => 'root', 'password' => '', 'dbname' => 'invo' ],
因为在我们所用数据库一般都是mysql,所以这里adapter可以省略不写,直接在use的时候指定到mysql,如下:
use PhalconDbAdapterPdoMysql as DbAdapter;
这样在注册的时候可以直接
$di->set('tutorial', function () use ($config) {
return new DbAdapter($config->tutorial->toArray());
});
$di->set('invo', function () use ($config) {
return new DbAdapter($config->invo->toArray());
});
注册两个数据库连接就可以了,在models中连接数据库需要用到
public function initialize(){
$this->setConnectionService('invo');
}
方法来指定连接的是哪个数据库;
Phalcon官方给的例子中注册数据库的时候代码是这样的:
$di->set('tutorial', function () use ($config) { return new DbAdapter(array( 'host' => $config->tutorial->host, 'username' => $config->tutorial->username, 'password' => $config->tutorial->password, 'dbname' => $config->tutorial->dbname )); }); $di->set('invo', function () use ($config) { return new DbAdapter(array( 'host' => $config->invo->host, 'username' => $config->invo->username, 'password' => $config->invo->password, 'dbname' => $config->invo->dbname )); });
这样做效果和上面的方法一样, 只是把拆分开了;
还有一种变体,是可以选择不同数据库类型的
$di->set('tutorial', function () use ($config) { $tutorial = $config->tutorial->toArray(); $dbClass = 'PhalconDbAdapterPdo\' . $tutorial['adapter']; unset($tutorial['adapter']); return new $dbClass($tutorial); }); $di->set('invo', function () use ($config) { $invo = $config->invo->toArray(); $dbClass = 'PhalconDbAdapterPdo\' . $invo['adapter']; unset($invo['adapter']); return new $dbClass($invo); });
这个方法需要在config.php中设置adapter设置数据库类型,对于需要连接不同数据库需求来说可以用;