基础控制器


基础控制器【Mb】源码及说明

所有的自定义控制器必须继承 Mb 基础控制器,基础控制器内置了一些常用的方法以便您的开发!您也可以扩展 Mb 来实现更为便捷的开发 ^_^

				
<?php

class Mb{// 基础类
	public $db;// 数据表操作对象
	public $dbName;// 数据表操作对象
	public $ip;// 获取客户端IP
	public $gets;// url 解析后获得的数据
	public $trace      = true;// 程序运行追踪
	public $postFilter = true;// 是否过滤 $_POST 数据内的 < > , 可防止跨站攻击
	protected $cacher  = null;// 缓存对象
	protected $cacheName;// 缓存名称
	
	public function __construct(){// 初始化基础构造
		$this->viewDir = Z_APP.'/'.Z_VIEW.'/';
		if($this->dbName != null){$this->db = db($this->dbName);}
		
		if(!empty($_POST)){// 过滤 $_POST
			define('Z_POST', true);
			if($this->postFilter){$_POST = str_replace(array('<','>', '"', "'"),array('<','>', '"', ''), $_POST);}
		}else{
			define('Z_POST', false);
		}
		// 过滤 $_GET
		if(!empty($_GET)){$_GET = str_replace(array('<','>', '"', "'"),array('<','>', '"',''), $_GET);}
		if(!empty($this->gets)){$this->gets = str_replace(array('<','>', '"', "'"),array('<','>', '"',''), $this->gets);}
	}
	
	public function index(){}// 默认 index
	
	public function display($tplName = null){// 视图展示
		$viewUrl = is_null($tplName) ? $this->viewDir.Z_C.'/'.Z_M.'.php' : $this->viewDir.$tplName;
		if(is_file($viewUrl)){include($viewUrl);}
	}
	
	protected function json($msg,$code = 200,$data = null){// 输出 json 形式的信息并终止程序运行
		$json = ['code' => $code, 'msg' => $msg];
		if($data){$json = array_merge($json,['data'=>$data]);}
		exit(json_encode($json));
	}
	
	protected function setLang($langType){// 语言包设置
		pgSetCookie('ueLang', $langType);
	}
	
	protected function getCacher(){// 获取缓存对象
		if(!empty($this->cacher)){return null;}
		$config         = c('cache');
		if(empty($config)){throw new Exception('缓存设置错误');}
		$type           = strtolower($config['type']);
		$className      = 'Mb\\tools\\caches\\'.$type.'Cacher';
		$this->cacher   = $className::getInstance($config);
	}
	
	protected function cache($name, $id = null, $queryMethod, $timer = 3600, $isSuper = true){// 进行缓存工作
		if(Z_CACHE){
			$queryRes    = $this->$queryMethod();
			$this->$name = $queryRes;
			return false;
		}
		$this->getCacher();
		$this->cacheName = getCacheName($name, $id, $isSuper);
		$cachedRes = $this->cacher->get($this->cacheName);
		if($cachedRes){$this->$name = $cachedRes; return true;}
		$queryRes = $this->$queryMethod();
		$this->cacher->set($this->cacheName, $queryRes, $timer);
		$this->$name = $queryRes;
	}
	
	public function delCache($name, $id = null, $isSuper = true){// 删除缓存
		$this->getCacher();
		if($name == '*'){
			$this->cacher->removeCacheAll();
		}else{
			$name = getCacheName($name, $id, $isSuper);
			$this->cacher->removeCache($name);
		}
	}
}