Zend Framework 2中与DB的动态连接

时间:2015-10-19 09:24:55

标签: php mysql zend-framework

我有3种类型的数据库:

  • Authen DB(固定地址和固定架构)

  • 配置数据库(固定地址和固定架构)

  • 服务DB(基于每项服务的动态地址和动态模式)

用户通过 Authen DB 进行登录和验证后。

根据配置数据库中的信息存储,ZF2应用程序中与服务相关的所有操作都应在相关的服务数据库上完成。

ZF2是否支持此案例?我该如何解决这个问题?

下面的代码是我的global.php和local.php。

global.php

return array(
    'db' => array(
        // primary database
        'driver'    => 'Pdo',
        'dsn'       => 'mysql:host=xxx.xxx.xxx.xxx;dbname=db_authen',
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ),
        // other database
        'adapters' => array(
            'db_config' => array(
               'driver'         => 'Pdo',
               'dsn'            => 'mysql:host=yyy.yyy.yyy.yyy;dbname=db_config',
               'driver_options' => array(
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ),
            ),
        ),
    ),
    'service_manager' => array(
        // primary database
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
            'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory'
        ),
        // other database
        'abstract_factories' => array(
            'Zend\Db\Adapter\AdapterAbstractServiceFactory',
        ),
    ),
);

local.php

return array(
    'db' => array(
        // primary database
        'username' => '*****',
        'password' => '*****',

        // other database
        'adapters' => array(
            'db_config' => array(
                'username' => '*****',
                'password' => '*****',
            ),
        ),
    ),
);

谢谢,

1 个答案:

答案 0 :(得分:3)

对(静态配置的)Auth DB进行身份验证并查询(静态配置的)Config DB以获取Service DB所需的动态信息后,您可以自己为服务DB实例化正确的DB适配器,使用类似的东西:

// Config from the Config DB, packaged into an array with keys that 
// are expected by \Zend\Db\Adapter\Adapter
$config = [
    'driver' => 'Pdo_Mysql', // for example
    'user' => 'my-dynamically-obtained-user',
    'password' => 'my-dynamically-obtained-password',
    'database' => 'my-dynamically-obtained-db-name',
    // etc
];
$adapter = new \Zend\Db\Adapter\Adapter($config);

// Now use the $adapter to build queries
$statement = $adapter->query('SELECT * FROM `mytable`');
$results = $statement->execute();

// iterate over the results, etc.

或者,您可以将$adapter提供给您创建的模型对象,该模型对象会隐藏来自使用者的特定于数据库的查询详细信息。

请参阅ZF2 docs for \Zend\Db\Adapter\Adapter