您好,我正在使用 Zend Framework 2 和 DoctrineORMModule。我需要访问不同的数据库连接并映射两组不同的模式。
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDODblib\Driver',
'params' => array(
'host' => 'HOST',
'port' => '1433',
'user' => 'USER',
'password' => 'PASS',
'dbname' => 'DBNAME',
)
)
)
),
/////////////
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => '127.0.0.1',
'port' => '3306',
'user' => 'root',
'password' => 'root',
'dbname' => 'test',
)
)
),
),
我在文档中找到了这个:
https://github.com/doctrine/DoctrineORMModule/blob/master/docs/configuration.md#how-to-use-two-connections
但它不是很描述。
谁能帮我?
最佳答案
use Doctrine\DBAL\DriverManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Configuration;
use Doctrine\DBAL\Connection;
/**
* @author Rafał Książek
*/
class DbFactory
{
/**
* @var array
*/
protected $config;
/**
* @return array
*/
public function getConfig()
{
return $this->config;
}
/**
* @param array $config
*/
public function __construct(array $config)
{
$this->config = $config;
}
/**
* Create connection to database
*
* @param string $dbName
* @return \Doctrine\DBAL\Connection
* @throws \InvalidArgumentException
* @throws \Exception
*/
public function getConnectionToDatabase($dbName)
{
$config = $this->getConfig();
if (empty($config['doctrine']['connection']['orm_default']['params'])) {
throw new \InvalidArgumentException('There is insufficient data in the configuration file!');
}
$params = $config['doctrine']['connection']['orm_default']['params'];
$params['dbname'] = $dbName;
$params['driver'] = 'pdo_mysql';
if (!($dbConnection = DriverManager::getConnection($params)))
throw new \Exception('There was a problem with establish connection to client db');
return $dbConnection;
}
/**
*
* @param \Doctrine\DBAL\Connection $dbConnection
* @param \Doctrine\ORM\Configuration $config
* @return \Doctrine\ORM\EntityManager
*/
public function getEntityManager(Connection $dbConnection, Configuration $config)
{
return EntityManager::create($dbConnection, $config);
}
}
使用方法:
$applicationConfig = $sm->get('config');
$em = $sm->get('Doctrine\ORM\EntityManager');
$emDefaultConfig = $em->getConnfiguration();
$dbFactory = new DbFactory($applicationConfig);
$anotherConnection = $dbFactory->getConnectionToDatabase('another_db');
$anotherEntityManager = $dbFactory->getEntityManager($anotherConnection, $emDefaultConfig);
$usersOnAnotherDb = $anotherEntityManager->getRepository('Application\Entity\User')->findAll();
关于database - 使用 Zend Framework 2 和 DoctrineORMModule 连接到多个数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15277277/