2

我想使用教义数据库配置访问教义中的 DBAL 层,我的教义数据库文件配置中有以下配置:database.local.php

return array(
  'doctrine' => array(
    'connection' => array(
      'orm_default' => array(
        'driverClass' => 'Doctrine\DBAL\Driver\PDOPgSql\Driver',
        'params' => array(
          'host'     => 'localhost',
          'port'     => '5432',
          'user'     => 'postgres',
          'password' => '123456',
          'dbname'   => 'test'
        )
      )
    )
  )
);

在我的控制器 IndexController.php

use Doctrine\DBAL\DriverManager;

public function testAction(){
   $conn = DriverManager::getConnection($params, $config);
}

我想在 getConnection 函数中使用上面的 db config,这可能吗?

4

2 回答 2

2

如果您的 db 配置中有一个 db 配置local.php,那么为什么不通过EntityManager? 像这样 :

public function testAction(){

 $em = ->getServiceLocator()
       ->get('Doctrine\ORM\EntityManager');

 $conn = $em->getConnection();
}

如果您想通过以下方式获得它DriverManager

$config = new \Doctrine\DBAL\Configuration();

$connectionParams = array(
      'host'     => 'localhost',
      'port'     => '5432',
      'user'     => 'postgres',
      'password' => '123456',
      'dbname'   => 'test'
      'driver' => 'pdo_pgsql',
);

$conn = DriverManager::getConnection($connectionParams, $config);

编辑 :

您还可以直接Doctrine\DBAL\Connection使用 Doctrine 提供的注册服务名称与您的实际数据库配置的实例:

$conn = $this->getServiceLocator()->get('doctrine.connection.orm_default');

作为DriverManager::getConnection()方法,这将返回Doctrine\DBAL\Connection包装底层驱动程序连接的 a。

于 2014-08-21T09:15:43.763 回答
1

当然。

首先你应该使用 ServiceLocator

ServiceLocator 自动注入到实现 \Zend\ServiceManager\ServiceLocatorAwareInterface 的类中

您的 zf2 控制器中的 AbstractActionController 已经实现了这个接口。

要在类中使用(通过示例进行模型),您应该声明实现和由接口设计的两个方法,setServiceLocator 和 getServiceLocator。

<?php
    namespace Security\Repository;

    use Zend\ServiceManager\ServiceLocatorInterface;
    use Zend\ServiceManager\ServiceLocatorAwareInterface;

    class Repository implements ServiceLocatorAwareInterface
    {
        protected $serviceLocator;

        public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
        {
            $this->serviceLocator = $serviceLocator;
        }

        public function getServiceLocator()
        {
            return $this->serviceLocator;
        }
    }

在 ZF2 上使用 ServiceLocator 很容易做任何事情。尝试了解如何获得 zf2 的全部功能。

$configArray = $this->getServiceLocator()->get('config');

$config = new \Doctrine\DBAL\Configuration();

$connectionParams = $configArray['doctrine']['connection']['orm_default']['params']

$conn = DriverManager::getConnection($connectionParams, $config);
于 2014-08-21T09:46:12.430 回答