使用 Zend Framework 连接到两个不同的数据库
我这里有一个完全用 Zend FW 编写的中型 Intranet 站点.Intranet 的数据库位于另一台服务器上.现在我需要使用一些新功能来扩展 Intranet.为了做到这一点,我需要连接到同一台服务器(和同一个 DBMS)上的另一个数据库.
I have here a medium sized intranet site which is written entirely in Zend FW. The database for the intranet is located on another server. Now I need to extend the intranet with some new functionality. In order to do this I need to connect to another database on the same server (and same DBMS).
现在的问题是:这样做的最佳方法是什么?我应该创建一个新的 Zend_Config 对象和一个新的 Zend_Db_Adapter 吗?或者我应该使用现有的并尝试使用use otherdbname;"在同一会话中连接到新数据库的语句?
The question is now: What is the best way to do this? Should I create a new Zend_Config object and a new Zend_Db_Adapter? Or should I use the existing one and try with the "use otherdbname;" statement to connect within the same session to the new database?
或者有更好的方法吗?
推荐答案
一种选择是从您的 bootstrap.php
中注册 2 个数据库句柄,每个连接一个.例如:
One option is to register 2 database handles from within your bootstrap.php
, one for each connection. E.g.:
$parameters = array(
'host' => 'xx.xxx.xxx.xxx',
'username' => 'test',
'password' => 'test',
'dbname' => 'test'
);
try {
$db = Zend_Db::factory('Pdo_Mysql', $parameters);
$db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
echo $e->getMessage();
die('Could not connect to database.');
} catch (Zend_Exception $e) {
echo $e->getMessage();
die('Could not connect to database.');
}
Zend_Registry::set('db', $db);
$parameters = array(
'host' => 'xx.xxx.xxx.xxx',
'username' => 'test',
'password' => 'test',
'dbname' => 'test'
);
try {
$db = Zend_Db::factory('Pdo_Mysql', $parameters);
$db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
echo $e->getMessage();
die('Could not connect to database.');
} catch (Zend_Exception $e) {
echo $e->getMessage();
die('Could not connect to database.');
}
Zend_Registry::set('db2', $db);
在您的控制器中(例如):
In your controllers (e.g.):
public function init()
{
$this->db = Zend_Registry::get('db');
$this->db2 = Zend_Registry::get('db2');
}
public function fooAction()
{
$data = $this->db2->fetchAll('select foo from blah');
...
}
相关文章