問題描述
我這里有一個完全用 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');
...
}
這篇關于使用 Zend Framework 連接到兩個不同的數據庫的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!