Zend Framework 2数据库连接问题

时间:2014-11-17 13:34:57

标签: php mysql zend-framework zend-framework2 zend-db-table

我使用ZF2来创建新的应用程序。 我们在控制器和模型文件下有关于数据库连接的一些问题。

我们已将所有数据库凭据放入" global.php"和" db.local.php"并在我们的" Module.php"中获取数据库适配器访问权限。文件,但我们没有在控制器和模型文件中获取数据库连接,也没有在控制器和模型下运行查询。

这是我的代码:

**global.php :**

return array(
    'db' => array(
            'driver'=> 'Pdo',
            'dsn'=> 'mysql:dbname=pick_fire;host=localhost',
            'driver_options' => array(
                    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
            ),
    ),
    'service_manager' => array(
            'factories' => array(
                    'Zend\Db\Adapter\Adapter'=> 'Zend\Db\Adapter\AdapterServiceFactory',
            ),
    ),
);

**db.local.php :** 

<?php
return array(
'db' => array(
    'driver'        => 'Pdo',
    'dsn'           => 'mysql:dbname=pick_fire;host=localhost',
    'username'      =>'root',
    'password'      =>'123456',
    'driver_options'=> array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
    ),
),
'service_manager' => array(
    'aliases' => array(
        'db' => 'Zend\Db\Adapter\Adapter',
    ),
),);

----------------------------------------------

**Module.php :** 

public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'mail.transport' => function (ServiceManager $serviceManager) {
                    $config = $serviceManager->get('Config'); 
                    $transport = new Smtp();                
                    $transport->setOptions(new SmtpOptions($config['mail']['transport']['options']));

                    return $transport;
                },
            ),
        );
        return array(
            'factories' => array(
                'adapter' =>  function($serviceManager) {
                    $config = $serviceManager->get('config');
                    $dbAdapter = new \Zend\Db\Adapter\Adapter($config['db']);
                    return $dbAdapter;
                }
            ),
        );
    }

----------------------------------------------

请建议我,如何获取数据库连接并在我们的控制器和模型文件中运行查询。

先谢谢你。

1 个答案:

答案 0 :(得分:4)

在你的getServiceConfig()中你有两个return语句......第二个从不被调用。 这应该有效:

**Module.php :** 

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'mail.transport' => function (ServiceManager $serviceManager) {
                $config = $serviceManager->get('Config'); 
                $transport = new Smtp();                
                $transport->setOptions(new SmtpOptions($config['mail']['transport']['options']));

                return $transport;
            },
            'adapter' =>  function($serviceManager) {
                $config = $serviceManager->get('config');
                $dbAdapter = new \Zend\Db\Adapter\Adapter($config['db']);
                return $dbAdapter;
            }
        ),
    );
}