Raf*_*ger 11 php database zend-framework zend-db
我这里有一个中型内部网站点,完全用Zend FW编写.Intranet的数据库位于另一台服务器上.现在我需要使用一些新功能扩展Intranet.为了做到这一点,我需要连接到同一服务器(和相同的DBMS)上的另一个数据库.
现在的问题是:最好的方法是什么?我应该创建一个新的Zend_Config对象和一个新的Zend_Db_Adapter吗?或者我应该使用现有的并尝试使用"use otherdbname;" 声明在同一会话中连接到新数据库?
或者有更好的方法吗?
kar*_*m79 11
一种选择是从您的内部注册2个数据库句柄bootstrap.php
,每个连接一个.例如:
$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);
Run Code Online (Sandbox Code Playgroud)
在您的控制器中(例如):
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');
...
}
Run Code Online (Sandbox Code Playgroud)