在zf2中获取doctrine db config



我想使用doctrine db config来访问doctrine中的DBAL层,我在doctrine db文件配置中有以下配置:database.local.php

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

和在我的控制器IndexController.php

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

我想在getConnection函数上面使用db配置,这是可能的吗?

如果您在local.php中有一个db配置,那么为什么不通过EntityManager访问它呢?就像这样:

public function testAction(){
 $em = ->getServiceLocator()
       ->get('DoctrineORMEntityManager');
 $conn = $em->getConnection();
}

如果你想让它通过DriverManager:

$config = new DoctrineDBALConfiguration();
$connectionParams = array(
      'host'     => 'localhost',
      'port'     => '5432',
      'user'     => 'postgres',
      'password' => '123456',
      'dbname'   => 'test'
      'driver' => 'pdo_pgsql',
);
$conn = DriverManager::getConnection($connectionParams, $config);
编辑:

您也可以使用Doctrine提供的已注册服务名称与您的实际db配置直接获得DoctrineDBALConnection的实例:

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

作为DriverManager::getConnection()方法,这将返回一个DoctrineDBALConnection,它包装了底层驱动程序连接。

可以。

首先你应该使用ServiceLocator

ServiceLocator被自动注入到实现ZendServiceManagerServiceLocatorAwareInterface的类

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

要在类中使用(例如模型),你应该声明implements和两个由接口设计的方法,setServiceLocator和getServiceLocator。

<?php
    namespace SecurityRepository;
    use ZendServiceManagerServiceLocatorInterface;
    use ZendServiceManagerServiceLocatorAwareInterface;
    class Repository implements ServiceLocatorAwareInterface
    {
        protected $serviceLocator;
        public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
        {
            $this->serviceLocator = $serviceLocator;
        }
        public function getServiceLocator()
        {
            return $this->serviceLocator;
        }
    }

使用ServiceLocator很容易在ZF2上做任何事情。试着理解它是如何工作的,以获得zf2的全部功能。

$configArray = $this->getServiceLocator()->get('config');
$config = new DoctrineDBALConfiguration();
$connectionParams = $configArray['doctrine']['connection']['orm_default']['params']
$conn = DriverManager::getConnection($connectionParams, $config);

最新更新