在我看来,使用 Doctrines ODM 并不是解决这个问题的正确方法。您仍然可以使用 Doctrine 连接到数据库并查询它们。但是,如果您没有实体类,那么使用实体管理器似乎是不合适的。
使用 Dotrine 进行连接处理
以下是如何使用该原则创建与数据库的连接Connection
class:
/** @var \Doctrine\Bundle\DoctrineBundle\ConnectionFactory $connectionFactory */
$connectionFactory = $this->getContainer()->get('doctrine.dbal.connection_factory');
$connection = $connectionFactory->createConnection(
array('pdo' => new \PDO("mysql:host=$hostname;dbname=$dbname", $username, $password))
);
现在你可以使用$connection
作为一个简单的PDO
object:
$connection->executeQuery('SELECT * FROM your_table');
您可以将此代码添加为service使其随处可用。
如果您想连接到不同域的不同数据库,您可以使用以下代码来识别域:
$this->getRequest()->getHost();
要访问域action做这个:
public function yourAction(Request $request, /* ... */)
{
// the Controller extends the Container. So need to get it here:
$connectionFactory = $this->get('doctrine.dbal.connection_factory');
// also access the domain like this:
$domain = $request->getHost();
}