Db.php 2.73 KB
<?php

class Q_Db
{

    /**
     *
     * Enter description here ...
     * @var Q_Db_Mysql_SqlMap_MapQuery
     */
    private static $mysql;

    /**
     * @var Q_Db_Mongo_Core_Base
     */
    private static $mongo;


    /**
     * mysql对比串
     * @var String
     */
    private static $mysqlDiffKey;

    /**
     * mongo 对比串
     * @var String
     */
    private static $mongoDiffKey;


    private static $fastPdo;

    /**
     * @param $router
     * @param null $configPath
     * @param bool $isCacheObj
     * @return Q_Db_Adapter_Pdo_Mysql
     */
    public static function mysql($router, $configPath = null, $isCacheObj = true)
    {
        return self::pdo($router, $configPath, $isCacheObj);
    }

    /**
     * Mongo 驱动
     * @static
     * @param $dbname
     * @param array $options
     * @return Q_Db_Mongo_Core_Base
     * @throws Q_Exception
     */
    public static function mongo($dbname, array $options = array())
    {
        if (empty($dbname)) {
            throw new Q_Exception(' Not Mongo DBname.');
        }
        $diffKey = md5(serialize($options) . '_' . $dbname);
        if ($diffKey == self::$mongoDiffKey) {
            return self::$mongo;
        }
        self::$mongoDiffKey = $diffKey;
        return self::$mongo = new Q_Db_Mongo_Core_Base($dbname, $options);
    }

    /**
     * @param $router
     * @param null $configPath
     * @param bool $isCacheObj
     * @return Q_Db_Adapter_Pdo_SqlMap
     * @throws Q_Exception
     */
    public static function pdo($router, $configPath = null, $isCacheObj = true)
    {
        if (empty($router)) {
            throw new Q_Exception('Q_Db Mysql, Not ' . $router);
        }
        $diffKey = md5(serialize($configPath) . '_' . $router);
        if ($diffKey == self::$mysqlDiffKey && $isCacheObj) {
            return self::$mysql;
        }
        self::$mysqlDiffKey = $diffKey;
        $options = array(
            'configPath' => $configPath
        );
        return self::$mysql = new Q_Db_Adapter_Pdo_SqlMap($router, $options);
    }

    /**
     * @param $router
     * @param array $options
     * @param bool $isCacheObj
     * @return Q_Db_Adapter_Pdo_FastSqlMap
     * @throws Q_Exception
     */
    static function fastPdo($router, array $options = array(), $isCacheObj = true)
    {
        if (empty($router)) {
            throw new Q_Exception('Router 不能为空. ');
        }
        if (empty($options['configPath'])) {
            throw new Q_Exception('SQL Map 配置路径不能为空(SQL Map ConfigPath is null.)');
        }
        if (isset(self::$fastPdo[$router]) && $isCacheObj) {
            return self::$fastPdo[$router];
        }
        return self::$fastPdo[$router] = new Q_Db_Adapter_Pdo_FastSqlMap($router, $options);
    }
}