使用Zend Framework连接到两个不同的数据库

时间:2009-10-04 12:59:37

标签: php database zend-framework zend-db

我这里有一个中型内部网站点,完全用Zend FW编写。 Intranet的数据库位于另一台服务器上。现在我需要使用一些新功能扩展Intranet。为了做到这一点,我需要连接到同一服务器(和相同的DBMS)上的另一个数据库。

现在的问题是:最好的方法是什么?我应该创建一个新的Zend_Config对象和一个新的Zend_Db_Adapter吗?或者我应该使用现有的并尝试使用“use otherdbname;”在同一会话中连接到新数据库的语句?

还是有更好的方法吗?

5 个答案:

答案 0 :(得分:11)

一种选择是在bootstrap.php内注册2个数据库句柄,每个连接一个。 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);

在您的控制器中(例如):

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');
    ...
}

答案 1 :(得分:3)

我认为这取决于您切换数据库的频率。使用两个不同的适配器可以更清晰地区分这两个数据库,这将是我的偏好。

当您在单个适配器上切换数据库时,您肯定很难跟踪哪个数据库当前活动 - 请记住,您的数据库连接很可能是传递的单例在模块之间,它们的控制器和它们各自的模型之间。

第三个选项是在整个应用程序中使用显式表名。例如,MySQL提供db_name.table_name - 语法来处理同一服务器上不同数据库中的表。默认数据库无关紧要,Zend_Db_TableZend_Db_Select支持此语法。

修改

我必须补充说,只有当您的数据库用户对您要使用的所有数据库,表和列具有相应的访问权限时,选项2和3才有效。如果您的数据库在每个数据库上需要不同的用户,则选项1将是唯一的选项。

答案 2 :(得分:3)

我正在使用此Config.ini您也可以使用它:

[production]
#Debug output
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
# Include path
includePaths.library = APPLICATION_PATH "/../library"
# Bootstrap
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
# Front Controller
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.env = APPLICATION_ENV
# Layout
#resources.layout.layout = "layout"
#resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
# Views
resources.view.encoding = "UTF-8"
resources.view.basePath = APPLICATION_PATH "/views/"
# Database
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "world"
resources.db.isDefaultTableAdapter = true
# Session
resources.session.save_path = APPLICATION_PATH "/../data/session"
resources.session.remember_me_seconds = 864000
[testing : production]
#Debug output
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
# Database
resources.db.params.dbname = "myproject_testing"
[development : production]
#Debug output
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
# Database
resources.db.params.dbname = "myproject_development"

如果您需要连接到另一个数据库,同时可以将数据库配置加倍,则可以将其用于生产,测试和开发环境:

resources.db2.adapter = "pdo_mysql"
resources.db2.params.host = "localhost"
resources.db2.params.username = "root"
resources.db2.params.password = ""
resources.db2.params.dbname = "world"
resources.db2.isDefaultTableAdapter = true

然后你可以在bootstap或任何你喜欢的地方加载它:) 而且它也很容易

答案 3 :(得分:2)

最好的方法之一是:

为数据库上的任何表创建新的模型表:

class Article extends Zend_Db_Table_Abstract  
{    
    protected $_name = 'id';
    public  function __construct()  {
        $adaptor = new Zend_Db_Adapter_Pdo_Mysql(array(
            'host'     => 'localhost',
            'username' => 'username',
            'password' => 'password',
            'dbname'   => 'database'

        ));
        $this->_db = $adaptor;
        parent::__construct();
    }

    // your functions goes here
    public function add($data) {
        // any syntax
    }
}

答案 4 :(得分:2)

从我发现here开始,为了在Zend应用程序中使用不同的数据库,您可以根据需要采用以下两种方式之一:

- 两个数据库拥有相同的主机/用户

您可以指定要在模型中初始化$_schema变量的数据库,如下所示:

class Customer extends Zend_Db_Table_Abstract
{
    protected $_name   = 'customer';
    protected $_schema = 'db_name';

    ....
}

- 为两个数据库提供不同的主机/用户

application.ini中,您必须按如下方式为两个数据库编写配置:

resources.multidb.local.adapter                 = pdo_mysql
resources.multidb.local.host                    = localhost
resources.multidb.local.username                = user
resources.multidb.local.password                = ******
resources.multidb.local.dbname                  = db_name_1
resources.multidb.local.default                 = true

resources.multidb.remote.adapter                = pdo_mysql
resources.multidb.remote.host                   = remote_host
resources.multidb.remote.username               = user
resources.multidb.remote.password               = ******
resources.multidb.remote.dbname                 = db_name_2
resources.multidb.remote.default                = false

_initDbRegistry块添加到bootstrap会将数据库添加到注册表中,因此您将能够访问它们:

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    /**
     * Add databases to the registry
     * 
     * @return void
     */
    public function _initDbRegistry()
    {
        $this->bootstrap('multidb');
        $multidb = $this->getPluginResource('multidb');
        Zend_Registry::set('db_local', $multidb->getDb('local')); //db_local is going to be the name of the local adapter
        Zend_Registry::set('db_remote', $multidb->getDb('remote')); //db_remote is going to be the name of the remote adapter
    }

}

现在,您可以为每个模型指定要使用的适配器,如下所示:

class Customer extends Zend_Db_Table_Abstract
{
    protected $_name    = 'customer';
    protected $_schema  = 'db_name_1';
    protected $_adapter = 'db_local'; //Using the local adapter

    ....
}

class Product extends Zend_Db_Table_Abstract
{
    protected $_name    = 'product';
    protected $_schema  = 'db_name_2';
    protected $_adapter = 'db_remote'; //Using the remote adapter

    ....
}