symfony2 动态数据库连接使用学说

2022-01-16 00:00:00 php mysql symfony doctrine doctrine-orm

我试图在 Symfony 2 中使用教义建立多个数据库连接,但无法做到.

I am trying to have multiple database connection in Symfony 2 with doctrine but not able to do so.

我在 Google 和 stack-overflow 中进行了广泛的搜索,但到处都是通过 config.yml 文件或动态数据库完成的,其中所有 DB 都具有相同的 schema/entities .

I have searched extensively in Google and stack-overflow but everywhere it's done via config.yml file or dynamic database where all DB's have same schema/entities .

但就我而言,数据库是根据子域确定的,并且所有子域的数据库架构都不相同.

例如:
test1.example.com => 应该加载 test1 db
test2.example.com => 将加载 test2 db

Ex:
test1.example.com => Should load test1 db
test2.example.com => Will load test2 db

test1 和 test2 DB 都是不同的,都是在 DB 级别创建的,并且在学说中没有实体条目.

谁能帮我在 Symfony 2 中做到这一点.

Can anyone please help me how to do this in Symfony 2.

推荐答案

在我看来,使用 Doctrines ODM 并不是解决这个问题的正确方法.你仍然可以使用 Doctrine 连接到数据库并查询它们.但是如果你没有实体类,那么使用实体管理器似乎是不合适的.

It seems to me that using Doctrines ODM is not the right way to approach this. You can still use Doctrine to connect to databases and query them. But if you have no entity classes the use of an entity manager seems to be inappropriate.

以下是您如何使用教义 Connection 类创建与数据库的连接:

Here is how you create a connection to a Database with the doctrine Connection class:

/** @var DoctrineBundleDoctrineBundleConnectionFactory $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 对象:

Now you can use $connection as a simple PDO object:

$connection->executeQuery('SELECT * FROM your_table');

您可以将此代码添加为服务,使其随处可访问.
如果您想为不同的域连接到不同的数据库,您可以使用此代码来识别域:

You could add this code as a service to make it accessible everywhere.
If you want to connect to a different database for a different domain you can use this code to identify the domain:

$this->getRequest()->getHost();

要在 action 中访问域,请执行以下操作:

To access the domain in an action do this:

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();
}

相关文章