<?php
/**
 * A class for managing db connections.
 *
 * This class provides a way to get (singleton factory) a db connection from a
 * dsn, instantiating it in the process, if necessary.
 */
class db
{
    /**
     * @var array The connections.
     */
    protected static $connection = array();

    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.

    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.

    /**
     * Gets a db connection.
     * 
     * @param string (optional) $name The name.
     * @throws outofrangeexception If the name does not exist.
     * @return db_connection The object.
     */
    public static function get($name = 'default')
    {
        if (!array_key_exists($name, self::$connection))
        {
            throw new outofrangeexception('Connection ' . $name . ' does not exist.');
        }
        
        if (!self::$connection[$name] instanceof db_connection)
        {
            $c = &self::$connection[$name];
            self::$connection[$name] = new db_connection($c[0], $c[1], $c[2], $c[3]);
        }
        
        return self::$connection[$name];
    }
    
    /**
     * Sets a db connection.
     * 
     * @param string $dsn The dsn.
     * @param string (optional) $user The user.
     * @param string (optional) $password The password.
     * @param array (optional) $option The connection options.
     * @param string (optional) $name The name.
     */
    public static function set($dsn, $user = null, $password = null, array $option = array(), $name = 'default')
    {
        self::$connection[$name] = array($dsn, $user, $password, $option); // Lazy.
    }
    
    /**
     * Gets a query object by connection name.
     * 
     * @param string (optional) $name The name.
     * @return db_query The object.
     */
    public static function query($name = 'default')
    {
        return self::get($name)->query();
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
