connecting to two different databases with Zend Framework(使用 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');
...
}
这篇关于使用 Zend Framework 连接到两个不同的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Zend Framework 连接到两个不同的数据库
基础教程推荐
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- 将变量从树枝传递给 js 2022-01-01
- php中的foreach复选框POST 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- php中的PDF导出 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
