Connection management - Managing connections.php 1.63 KB
Newer Older
1

hansbrix's avatar
hansbrix committed
2 3 4 5 6 7 8 9 10
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

zYne's avatar
zYne committed
11
$manager = Doctrine_Manager::getInstance();
hansbrix's avatar
hansbrix committed
12 13 14

// open first connection
 
zYne's avatar
zYne committed
15
$conn = $manager->openConnection(new PDO('dsn','username','password'), 'connection 1');
hansbrix's avatar
hansbrix committed
16 17 18 19 20 21 22 23 24 25 26 27
</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
 
zYne's avatar
zYne committed
28
$conn = Doctrine_Manager::connection(new PDO('dsn','username','password'), 'connection 1');
hansbrix's avatar
hansbrix committed
29

zYne's avatar
zYne committed
30
$conn2 = Doctrine_Manager::connection();
hansbrix's avatar
hansbrix committed
31

zYne's avatar
zYne committed
32
// $conn2 == $conn
hansbrix's avatar
hansbrix committed
33 34 35 36 37 38 39 40 41 42 43 44 45
</code>





The current connection is the lastly opened connection. 



<code type="php">
// open second connection

zYne's avatar
zYne committed
46
$conn2 = $manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');
hansbrix's avatar
hansbrix committed
47

zYne's avatar
zYne committed
48
$manager->getCurrentConnection(); // $conn2
zYne's avatar
zYne committed
49
</code>
hansbrix's avatar
hansbrix committed
50 51 52 53 54 55 56 57



You can change the current connection by calling setCurrentConnection(). 



<code type="php">
zYne's avatar
zYne committed
58
$manager->setCurrentConnection('connection 1');
hansbrix's avatar
hansbrix committed
59

zYne's avatar
zYne committed
60
$manager->getCurrentConnection(); // $conn
zYne's avatar
zYne committed
61

hansbrix's avatar
hansbrix committed
62 63 64 65 66 67 68 69 70 71 72 73
</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

zYne's avatar
zYne committed
74
foreach($manager as $conn) {
hansbrix's avatar
hansbrix committed
75 76

}
zYne's avatar
zYne committed
77
</code>
78