Manager.php 15.1 KB
Newer Older
lsmith's avatar
lsmith committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
/**
 *
lsmith's avatar
lsmith committed
23
 * Doctrine_Manager is the base component of all doctrine based projects.
lsmith's avatar
lsmith committed
24 25 26 27 28 29 30 31 32 33
 * It opens and keeps track of all connections (database connections).
 *
 * @package     Doctrine
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
lsmith's avatar
lsmith committed
34 35
class Doctrine_Manager extends Doctrine_Configurable implements Countable, IteratorAggregate
{
lsmith's avatar
lsmith committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    /**
     * @var array $connections      an array containing all the opened connections
     */
    private $connections   = array();
    /**
     * @var array $bound            an array containing all components that have a bound connection
     */
    private $bound          = array();
    /**
     * @var integer $index          the incremented index
     */
    private $index      = 0;
    /**
     * @var integer $currIndex      the current connection index
     */
    private $currIndex  = 0;
    /**
     * @var string $root            root directory
     */
    private $root;
    /**
     * @var Doctrine_Null $null     Doctrine_Null object, used for extremely fast null value checking
     */
    private $null;
zYne's avatar
zYne committed
60 61 62 63 64 65 66 67
    /**
     * @var array $driverMap
     */
    private $driverMap        = array('oracle'     => 'oci8',
                                      'postgres'   => 'pgsql',
                                      'oci'        => 'oci8',
                                      'sqlite2'    => 'sqlite',
                                      'sqlite3'    => 'sqlite');
lsmith's avatar
lsmith committed
68 69 70 71 72
    /**
     * constructor
     *
     * this is private constructor (use getInstance to get an instance of this class)
     */
lsmith's avatar
lsmith committed
73 74
    private function __construct()
    {
lsmith's avatar
lsmith committed
75 76 77 78 79 80 81 82 83 84 85
        $this->root = dirname(__FILE__);
        $this->null = new Doctrine_Null;

        Doctrine_Record::initNullObject($this->null);
        Doctrine_Collection::initNullObject($this->null);
        Doctrine_Record_Iterator::initNullObject($this->null);
        Doctrine_Validator::initNullObject($this->null);
    }
    /**
     * @return Doctrine_Null
     */
lsmith's avatar
lsmith committed
86 87
    final public function getNullObject()
    {
lsmith's avatar
lsmith committed
88 89 90 91 92 93 94 95
        return $this->null;
    }
    /**
     * setDefaultAttributes
     * sets default attributes
     *
     * @return boolean
     */
lsmith's avatar
lsmith committed
96 97
    final public function setDefaultAttributes()
    {
lsmith's avatar
lsmith committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        static $init = false;
        if ( ! $init) {
            $init = true;
            $attributes = array(
                        Doctrine::ATTR_FETCHMODE        => Doctrine::FETCH_IMMEDIATE,
                        Doctrine::ATTR_BATCH_SIZE       => 5,
                        Doctrine::ATTR_COLL_LIMIT       => 5,
                        Doctrine::ATTR_LISTENER         => new Doctrine_EventListener(),
                        Doctrine::ATTR_LOCKMODE         => 1,
                        Doctrine::ATTR_VLD              => false,
                        Doctrine::ATTR_AUTO_LENGTH_VLD  => true,
                        Doctrine::ATTR_AUTO_TYPE_VLD    => true,
                        Doctrine::ATTR_CREATE_TABLES    => true,
                        Doctrine::ATTR_QUERY_LIMIT      => Doctrine::LIMIT_RECORDS,
                        Doctrine::ATTR_IDXNAME_FORMAT   => "%s_idx",
                        Doctrine::ATTR_SEQNAME_FORMAT   => "%s_seq",
                        Doctrine::ATTR_QUOTE_IDENTIFIER => false,
                        Doctrine::ATTR_SEQCOL_NAME      => 'id',
                        Doctrine::ATTR_PORTABILITY      => Doctrine::PORTABILITY_ALL,
zYne's avatar
zYne committed
117
                        Doctrine::ATTR_EXPORT           => Doctrine::EXPORT_NONE,
lsmith's avatar
lsmith committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
                        );
            foreach ($attributes as $attribute => $value) {
                $old = $this->getAttribute($attribute);
                if ($old === null) {
                    $this->setAttribute($attribute,$value);
                }
            }
            return true;
        }
        return false;
    }
    /**
     * returns the root directory of Doctrine
     *
     * @return string
     */
lsmith's avatar
lsmith committed
134 135
    final public function getRoot()
    {
lsmith's avatar
lsmith committed
136 137 138 139 140 141 142 143 144
        return $this->root;
    }
    /**
     * getInstance
     * returns an instance of this class
     * (this class uses the singleton pattern)
     *
     * @return Doctrine_Manager
     */
lsmith's avatar
lsmith committed
145 146
    public static function getInstance()
    {
lsmith's avatar
lsmith committed
147 148 149 150 151 152 153 154
        static $instance;
        if ( ! isset($instance)) {
            $instance = new self();
        }
        return $instance;
    }
    /**
     * connection
lsmith's avatar
lsmith committed
155
     *
lsmith's avatar
lsmith committed
156 157 158
     * if the adapter parameter is set this method acts as
     * a short cut for Doctrine_Manager::getInstance()->openConnection($adapter, $name);
     *
lsmith's avatar
lsmith committed
159
     * if the adapter paramater is not set this method acts as
lsmith's avatar
lsmith committed
160 161 162 163 164 165 166
     * a short cut for Doctrine_Manager::getInstance()->getCurrentConnection()
     *
     * @param PDO|Doctrine_Adapter_Interface $adapter   database driver
     * @param string $name                              name of the connection, if empty numeric key is used
     * @throws Doctrine_Manager_Exception               if trying to bind a connection with an existing name
     * @return Doctrine_Connection
     */
lsmith's avatar
lsmith committed
167 168
    public static function connection($adapter = null, $name = null)
    {
lsmith's avatar
lsmith committed
169 170 171 172 173
        if ($adapter == null) {
            return Doctrine_Manager::getInstance()->getCurrentConnection();
        } else {
            return Doctrine_Manager::getInstance()->openConnection($adapter, $name);
        }
lsmith's avatar
lsmith committed
174
    }
lsmith's avatar
lsmith committed
175 176 177 178 179 180 181
    /**
     * openConnection
     * opens a new connection and saves it to Doctrine_Manager->connections
     *
     * @param PDO|Doctrine_Adapter_Interface $adapter   database driver
     * @param string $name                              name of the connection, if empty numeric key is used
     * @throws Doctrine_Manager_Exception               if trying to bind a connection with an existing name
zYne's avatar
zYne committed
182
     * @throws Doctrine_Manager_Exception               if trying to open connection for unknown driver
lsmith's avatar
lsmith committed
183 184
     * @return Doctrine_Connection
     */
185
    public function openConnection($adapter, $name = null, $setCurrent = true)
lsmith's avatar
lsmith committed
186
    {
lsmith's avatar
lsmith committed
187 188 189 190
        if ( ! ($adapter instanceof PDO) && ! in_array('Doctrine_Adapter_Interface', class_implements($adapter))) {
            throw new Doctrine_Manager_Exception("First argument should be an instance of PDO or implement Doctrine_Adapter_Interface");
        }

191 192 193 194
        if ($adapter instanceof Doctrine_Db) {
            $adapter->setName($name);
        }

lsmith's avatar
lsmith committed
195 196 197 198 199 200
        // initialize the default attributes
        $this->setDefaultAttributes();

        if ($name !== null) {
            $name = (string) $name;
            if (isset($this->connections[$name])) {
201
                return $this->connections[$name];
lsmith's avatar
lsmith committed
202 203 204 205 206
            }
        } else {
            $name = $this->index;
            $this->index++;
        }
zYne's avatar
zYne committed
207

zYne's avatar
zYne committed
208
        switch ($adapter->getAttribute(Doctrine::ATTR_DRIVER_NAME)) {
209 210 211 212 213 214 215 216 217 218 219 220 221 222
            case 'mysql':
                $this->connections[$name] = new Doctrine_Connection_Mysql($this, $adapter);
                break;
            case 'sqlite':
                $this->connections[$name] = new Doctrine_Connection_Sqlite($this, $adapter);
                break;
            case 'pgsql':
                $this->connections[$name] = new Doctrine_Connection_Pgsql($this, $adapter);
                break;
            case 'oci':
            case 'oracle':
                $this->connections[$name] = new Doctrine_Connection_Oracle($this, $adapter);
                break;
            case 'mssql':
zYne's avatar
zYne committed
223
            case 'dblib':
224 225 226 227 228 229 230 231 232 233 234 235
                $this->connections[$name] = new Doctrine_Connection_Mssql($this, $adapter);
                break;
            case 'firebird':
                $this->connections[$name] = new Doctrine_Connection_Firebird($this, $adapter);
                break;
            case 'informix':
                $this->connections[$name] = new Doctrine_Connection_Informix($this, $adapter);
                break;
            case 'mock':
                $this->connections[$name] = new Doctrine_Connection_Mock($this, $adapter);
                break;
            default:
236
                throw new Doctrine_Manager_Exception('Unknown connection driver '. $adapter->getAttribute(Doctrine::ATTR_DRIVER_NAME));
lsmith's avatar
lsmith committed
237
        };
238

239
        if ($setCurrent) {
240
            $this->currIndex = $name;
241
        }
lsmith's avatar
lsmith committed
242 243 244 245 246 247 248 249
        return $this->connections[$name];
    }
    /**
     * getConnection
     * @param integer $index
     * @return object Doctrine_Connection
     * @throws Doctrine_Manager_Exception   if trying to get a non-existent connection
     */
lsmith's avatar
lsmith committed
250 251
    public function getConnection($name)
    {
lsmith's avatar
lsmith committed
252 253 254
        if ( ! isset($this->connections[$name])) {
            throw new Doctrine_Manager_Exception('Unknown connection: ' . $name);
        }
zYne's avatar
zYne committed
255

lsmith's avatar
lsmith committed
256 257
        return $this->connections[$name];
    }
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    /** 
     * getComponentAlias
     * retrieves the alias for given component name 
     * if the alias couldn't be found, this method returns the given
     * component name
     *
     * @param string $componentName
     * @return string                   the component alias
     */
    public function getComponentAlias($componentName)
    {
        if (isset($this->componentAliases[$componentName])) {
            return $this->componentAliases[$componentName];
        }
        
        return $componentName;
    }
    /**
     * sets an alias for given component name
     * very useful when building a large framework with a possibility
     * to override any given class
     *
     * @param string $componentName         the name of the component
     * @param string $alias
     * @return Doctrine_Manager
     */
    public function setComponentAlias($componentName, $alias) 
    {
        $this->componentAliases[$componentName] = $alias;
        
        return $this;
    }
zYne's avatar
zYne committed
290 291 292
    /**
     * getConnectionName
     *
zYne's avatar
zYne committed
293 294
     * @param Doctrine_Connection $conn     connection object to be searched for
     * @return string                       the name of the connection
zYne's avatar
zYne committed
295 296 297
     */
    public function getConnectionName(Doctrine_Connection $conn) 
    {
zYne's avatar
zYne committed
298
        return array_search($conn, $this->connections, true);
zYne's avatar
zYne committed
299
    }
lsmith's avatar
lsmith committed
300 301 302 303 304 305 306 307 308 309
    /**
     * bindComponent
     * binds given component to given connection
     * this means that when ever the given component uses a connection
     * it will be using the bound connection instead of the current connection
     *
     * @param string $componentName
     * @param string $connectionName
     * @return boolean
     */
lsmith's avatar
lsmith committed
310 311
    public function bindComponent($componentName, $connectionName)
    {
lsmith's avatar
lsmith committed
312 313 314 315 316 317 318 319
        $this->bound[$componentName] = $connectionName;
    }
    /**
     * getConnectionForComponent
     *
     * @param string $componentName
     * @return Doctrine_Connection
     */
lsmith's avatar
lsmith committed
320 321
    public function getConnectionForComponent($componentName = null)
    {
lsmith's avatar
lsmith committed
322 323 324 325 326
        if (isset($this->bound[$componentName])) {
            return $this->getConnection($this->bound[$componentName]);
        }
        return $this->getCurrentConnection();
    }
lsmith's avatar
lsmith committed
327
    /**
lsmith's avatar
lsmith committed
328 329 330 331 332 333 334 335
     * getTable
     * this is the same as Doctrine_Connection::getTable() except
     * that it works seamlessly in multi-server/connection environment
     *
     * @see Doctrine_Connection::getTable()
     * @param string $componentName
     * @return Doctrine_Table
     */
lsmith's avatar
lsmith committed
336 337
    public function getTable($componentName)
    {
lsmith's avatar
lsmith committed
338 339 340 341 342 343 344 345
        return $this->getConnectionForComponent($componentName)->getTable($componentName);
    }
    /**
     * closes the connection
     *
     * @param Doctrine_Connection $connection
     * @return void
     */
lsmith's avatar
lsmith committed
346 347
    public function closeConnection(Doctrine_Connection $connection)
    {
lsmith's avatar
lsmith committed
348
        $connection->close();
zYne's avatar
zYne committed
349 350 351 352 353 354
        
        $key = array_search($connection, $this->connections, true);

        if ($key !== false) {
            unset($this->connections[$key]);
        }
355
        $this->currIndex = key($this->connections);
zYne's avatar
zYne committed
356

lsmith's avatar
lsmith committed
357 358 359 360 361 362 363 364
        unset($connection);
    }
    /**
     * getConnections
     * returns all opened connections
     *
     * @return array
     */
lsmith's avatar
lsmith committed
365 366
    public function getConnections()
    {
lsmith's avatar
lsmith committed
367 368 369 370 371 372 373 374 375 376
        return $this->connections;
    }
    /**
     * setCurrentConnection
     * sets the current connection to $key
     *
     * @param mixed $key                        the connection key
     * @throws InvalidKeyException
     * @return void
     */
lsmith's avatar
lsmith committed
377 378
    public function setCurrentConnection($key)
    {
lsmith's avatar
lsmith committed
379 380 381 382 383 384
        $key = (string) $key;
        if ( ! isset($this->connections[$key])) {
            throw new InvalidKeyException();
        }
        $this->currIndex = $key;
    }
zYne's avatar
zYne committed
385 386 387 388 389 390 391 392 393 394 395
    /**
     * contains
     * whether or not the manager contains specified connection
     *
     * @param mixed $key                        the connection key
     * @return boolean
     */
    public function contains($key) 
    {
        return isset($this->connections[$key]);
    }
lsmith's avatar
lsmith committed
396 397 398 399 400 401
    /**
     * count
     * returns the number of opened connections
     *
     * @return integer
     */
lsmith's avatar
lsmith committed
402 403
    public function count()
    {
lsmith's avatar
lsmith committed
404 405 406 407 408 409 410 411
        return count($this->connections);
    }
    /**
     * getIterator
     * returns an ArrayIterator that iterates through all connections
     *
     * @return ArrayIterator
     */
lsmith's avatar
lsmith committed
412 413
    public function getIterator()
    {
lsmith's avatar
lsmith committed
414 415 416 417 418 419 420 421 422
        return new ArrayIterator($this->connections);
    }
    /**
     * getCurrentConnection
     * returns the current connection
     *
     * @throws Doctrine_Connection_Exception       if there are no open connections
     * @return Doctrine_Connection
     */
lsmith's avatar
lsmith committed
423 424
    public function getCurrentConnection()
    {
lsmith's avatar
lsmith committed
425 426 427 428 429 430 431 432 433 434 435 436
        $i = $this->currIndex;
        if ( ! isset($this->connections[$i])) {
            throw new Doctrine_Connection_Exception();
        }
        return $this->connections[$i];
    }
    /**
     * __toString
     * returns a string representation of this object
     *
     * @return string
     */
lsmith's avatar
lsmith committed
437 438
    public function __toString()
    {
lsmith's avatar
lsmith committed
439 440 441 442 443 444 445
        $r[] = "<pre>";
        $r[] = "Doctrine_Manager";
        $r[] = "Connections : ".count($this->connections);
        $r[] = "</pre>";
        return implode("\n",$r);
    }
}