<?php
/*
* 项目: iOrange(橘子)
* 作者: 离家出走(yzxh24)
* Email: yzxh24@gmail.com
* 主页: www.iorange.cc
*/
/* vim: set ts=4 sw=4: */
function iLoad($class)
{
	$model = ROOT_PATH . 'model/' . strtolower($class) . '.php';
	if (is_file($model))
	{
		require_once $model;
	}
    else
    {
        $classFile = ROOT_PATH . 'libs/class/'.$class . '.php';
        if (is_file($classFile))
        {
            require_once $classFile;
        }

        if (preg_match('/_/is', $class))
        {
            $classFile = ROOT_PATH . 'libs/class/' . preg_replace('/_/is', DIRECTORY_SEPARATOR, $class) . '.php';
            if (is_file($classFile))
            {
                require_once $classFile;
            }
        }
    }
}
spl_autoload_register('iLoad');

require_once ROOT_PATH . 'include/Db.class.php';

class Model
{
	public $_db = null;
	
	public static $_self = array();
	
	public $_cache = null;
	
	public function __construct()
	{
		global $cache;
		if (is_null($this->_db))
		{
			$this->_db = Db::getInstance();
		}
		
		if (is_null($this->_cache))
		{
			$this->_cache = $cache;
		}
	}

	public static function single($className = __CLASS__)
	{
		if (!isset(self::$_self[$className]))
		{
			self::$_self[$className] = new $className;
		}
		
		return self::$_self[$className];
	}

    public function Db()
    {
        return $this->_db;
    }

    public function Cache()
    {
        return $this->_cache;
    }
	
	public static function table()
	{
		throw new Exception('子类必须实现此方法');
	}
	
	public static function getEscapeString($key, $value, $operator = '=')
	{
		return self::escape($key) . $operator . self::quote($value);
	}
	
	public static function quote($value)
	{
		return "'" . $value . "'";
	}
	
	public static function escape($key)
	{
		return '`' . $key . '`';
	}
}