1
0
mirror of synced 2024-12-15 15:46:02 +03:00
doctrine2/manual/docs/Connection management - Managing connections.php

79 lines
1.6 KiB
PHP
Raw Normal View History

2007-04-14 01:49:11 +04:00
From the start Doctrine has been designed to work with multiple connections. Unless separately specified Doctrine always uses the current connection
for executing the queries. The following example uses openConnection() second argument as an optional
connection alias.
<code type="php">
// Doctrine_Manager controls all the connections
2007-05-07 19:42:26 +04:00
$manager = Doctrine_Manager::getInstance();
2007-04-14 01:49:11 +04:00
// open first connection
2007-05-07 19:44:20 +04:00
$conn = $manager->openConnection(new PDO('dsn','username','password'), 'connection 1');
2007-04-14 01:49:11 +04:00
</code>
For convenience Doctrine_Manager provides static method connection() which opens new connection when arguments are given to it and returns the current
connection when no arguments have been speficied.
<code type="php">
// open first connection
2007-05-07 19:42:26 +04:00
$conn = Doctrine_Manager::connection(new PDO('dsn','username','password'), 'connection 1');
2007-04-14 01:49:11 +04:00
2007-05-07 19:42:26 +04:00
$conn2 = Doctrine_Manager::connection();
2007-04-14 01:49:11 +04:00
2007-05-07 19:40:22 +04:00
// $conn2 == $conn
2007-04-14 01:49:11 +04:00
</code>
The current connection is the lastly opened connection.
<code type="php">
// open second connection
2007-05-07 19:42:26 +04:00
$conn2 = $manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');
2007-04-14 01:49:11 +04:00
2007-05-07 19:42:26 +04:00
$manager->getCurrentConnection(); // $conn2
2007-05-07 19:41:08 +04:00
</code>
2007-04-14 01:49:11 +04:00
You can change the current connection by calling setCurrentConnection().
<code type="php">
2007-05-07 19:42:26 +04:00
$manager->setCurrentConnection('connection 1');
2007-04-14 01:49:11 +04:00
2007-05-07 19:42:26 +04:00
$manager->getCurrentConnection(); // $conn
2007-05-07 19:40:22 +04:00
2007-04-14 01:49:11 +04:00
</code>
You can iterate over the opened connection by simple passing the manager object to foreach clause. This is possible since Doctrine_Manager implements
special IteratorAggregate interface.
<code type="php">
// iterating through connections
2007-05-07 19:42:26 +04:00
foreach($manager as $conn) {
2007-04-14 01:49:11 +04:00
}
2007-05-07 19:40:22 +04:00
</code>