root/trunk/src/main/php/net/stubbles/rdbms/stubDatabaseConnectionProvider.php

Revision 1373, 2.2 kB (checked in by mikey, 4 months ago)

refactored net::stubbles::rdbms::stubDatabaseConnectionProvider to make use of the new injection provider features

Line 
1 <?php
2 /**
3  * IOC provider for database connections.
4  *
5  * @author      Frank Kleine <mikey@stubbles.net>
6  * @package     stubbles
7  * @subpackage  rdbms
8  */
9 stubClassLoader::load('net::stubbles::ioc::stubInjectionProvider',
10                       'net::stubbles::rdbms::stubDatabaseConnectionData',
11                       'net::stubbles::rdbms::stubDatabaseConnectionPool',
12                       'net::stubbles::rdbms::stubDatabaseException'
13 );
14 /**
15  * IOC provider for database connections.
16  *
17  * @package     stubbles
18  * @subpackage  rdbms
19  */
20 class stubDatabaseConnectionProvider extends stubBaseObject implements stubInjectionProvider
21 {
22     /**
23      * switch whether to fallback to default connection if no named connection exists
24      *
25      * @var  bool
26      */
27     protected $fallback = true;
28
29     /**
30      * constructor
31      *
32      * @param  bool  $fallback  whether to fallback to default connection if no named connection exists
33      */
34     public function __construct($fallback = true)
35     {
36         $this->fallback = $fallback;
37     }
38
39     /**
40      * returns the connection to be injected
41      *
42      * If a name is provided and a condition with this name exists this
43      * connection will be returned. If fallback is enabled and the named
44      * connection does not exist the default connection will be returned, if
45      * fallback is disabled a stubDatabaseException will be thrown.
46      *
47      * If no name is provided the default connection will be returned.
48      *
49      * @param   string                  $type
50      * @param   string                  $name  optional
51      * @return  stubDatabaseConnection
52      * @throws  stubDatabaseException
53      */
54     public function get($type, $name = null)
55     {
56         if (null !== $name) {
57             if (stubDatabaseConnectionPool::hasConnectionData($name) === true) {
58                 return stubDatabaseConnectionPool::getConnection($name);
59             }
60             
61             if (false === $this->fallback) {
62                 throw new stubDatabaseException('No connection and no dsn known for connection associated with id ' . $name);
63             }
64         }
65         
66         return stubDatabaseConnectionPool::getConnection(stubDatabaseConnectionData::DEFAULT_ID);
67     }
68 }
69 ?>
Note: See TracBrowser for help on using the browser.