2

doctrine db config を使用して doctrine の DBAL レイヤーにアクセスしたいのですが、doctrine db ファイル構成に次の構成があります: 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

にデータベース構成がある場合は、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\ConnectionDoctrine が提供する登録済みサービス名を実際のデータベース構成で使用するインスタンスを直接取得することもできます。

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

メソッドとして、これは基になるドライバー接続をラップDriverManager::getConnection()する を返します。Doctrine\DBAL\Connection

于 2014-08-21T09:15:43.763 に答える
1

もちろん。

まず、 ServiceLocator を使用する必要があります

ServiceLocator は、\Zend\ServiceManager\ServiceLocatorAwareInterface を実装するクラスに自動注入されます

zf2 コントローラーの AbstractActionController は、このインターフェースを既に実装しています。

クラス (例によるモデル) で使用するには、実装と、インターフェイスによって設計された 2 つのメソッド、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;
        }
    }

ServiceLocator を使用すると、ZF2 で何でも簡単に実行できます。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 に答える