0

我有一个需要从中传递自定义数据库查询的 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',
        ),
    ),
);
4

1 回答 1

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();
    }
}
于 2013-02-06T09:34:21.933 回答