<?php
/* * *********************************************************
 * [cml] (C)2012 - 3000 cml http://linhecheng.com
 * @Author  linhecheng<linhechengbush@live.com>
 * @Date: 13-6-26 上午11:23
 * @version  1.0 
 * cml框架 系统默认Model
 * *********************************************************** */

defined('CML_PATH') || exit();

class CmlModel
{
	/**
	 * @var array Db驱动实例
	 */
	private static $dbInstance = array();

	/**
	 * @var array Cache驱动实例
	 */
	private static $cacheInstance = array();

	/**
	 * 初始化
	 *
	 * @return void
	 */
	public function __construct()
	{

	}

	/**
	 * 获取db实例
	 *
	 * @param string $conf;
	 *
	 * @return DbMysql | DbPdoMysql
	 */
	public function db($conf = 'DEFAULT_DB')
	{
		$config = C($conf);
		$driver = 'Db'.$config['DRIVER'];
		if(isset(self::$dbInstance[$conf])) {
			return self::$dbInstance[$conf];
		} else {
			self::$dbInstance[$conf] = new $driver($config);
			return self::$dbInstance[$conf];
		}
	}

	/**
	 * 当程序连接N个db的时候用于释放于用连接以节省内存
	 *
	 * @param string $conf
	 */
	public function closeDb($conf = 'DEFAULT_DB')
	{
		//$this->db($conf)->close();释放对象时会执行析构回收
		unset(self::$dbInstance[$conf]);
	}

	/**
	 * 获取cache实例
	 *
	 * @param string $conf;
	 *
	 * @return CacheApc | CacheFile | CacheMemcache | CacheRedis
	 */
	public function cache($conf = 'DEFAULT_CACHE')
	{
		$config = C($conf);
		$driver = 'Cache'.$config['DRIVER'];
		if(isset(self::$cacheInstance[$conf])) {
			return self::$cacheInstance[$conf];
		} else {
			if($config['ON']) {
				self::$cacheInstance[$conf] = new $driver($config);
				return self::$cacheInstance[$conf];
			} else {
				throw_exception($conf.L('_NOT_OPEN_'));
				return false;
			}
		}
	}

	/**
	 * cache中有时从cache取，cache里没有时从db取 并写到cache
	 *
	 * @param string $key
	 *
	 * @return mixed
	 */
	public function dbCacheGet($key)
	{
		$val = $this->cache()->get($key);
		if(empty($val)) {
			$val = $this->db()->get($key);
			$this->cache()->set($key, $val);
		}
		return $val;
	}

	/**
	 * 同时存到cache和db
	 *
	 * @param string $key
	 * @param array $val
	 * @param bool $and
	 * @param int $expire
	 *
	 * @return bool
	 */
	public function dbCacheSet($key, $val, $and = true, $expire = 0)
	{
		$this->cache()->set($key, $val, $expire);
		$this->db()->set($key, $val, $and);
		return true;
	}

	/**
	 * 同时更新cache和db
	 *
	 * @param string $key
	 * @param array $val
	 * @param bool $and
	 * @param int $expire
	 *
	 * @return bool
	 */
	public function dbCacheUpdate($key, $val, $and = true, $expire = 0)
	{
		$this->cache()->update($key, $val, $expire);
		$this->db()->update($key, $val, $and);
		return true;
	}

	/**
	 * 同时从db和cache中删除
	 *
	 * @param string $key
	 *
	 * @return bool
	 */
	public function dbCacheDelete($key)
	{
		$this->cache()->delete($key);
		$this->db()->delete($key);
		return true;
	}

}