ZF2数据库对象

时间:2013-02-06 04:15:07

标签: zend-framework2

我有一个ZF2应用程序,我需要从中传递自定义数据库查询。我在local.php和global.php中设置了数据库凭据。从类中,如何获取数据库对象?

这是我的global.php:

return array(
    'db' => array(
        'driver' => 'Pdo',
        'dsn' => 'mysql:dbname=database_name;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',
        ),
    ),
);

1 个答案:

答案 0 :(得分:3)

获取数据库对象

在Module.php中

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'db_adapter' =>  function($sm) {
                $config = $sm->get('Configuration');
                return new \Zend\Db\Adapter\Adapter($config['db']);
            },
            'xyz_class_name' => function ($sm) {
                return new \WhatEver\Model\xyzMapper($sm->get('db_adapter'));
            },
        ),
    );
}

在xyzMapper中

namespace WhatEver\Model;

use Zend\Db\Adapter\Adapter;

class xyzMapper
{
    protected $adapter;

    /**
     * Make the Adapter object avilable as local prtected variable
     * @param Adapter $adapter - DB PDO PgSQL conn
     */
    public function __construct(Adapter $adapter = null)
    {
        $this->adapter = $adapter;
    }

    /**
     * @return result object
     */
    public function getdata()
    {
        $sql = "SELECT * FROM tbl";

        $statement = $this->adapter->query($sql);
        return $statement->execute();
    }
}