PHP中面向对象中的模板引擎类
admin
2023-02-11 14:20:09
0次
_checkDir($tplDir)) {
				$this->tplDir = rtrim($tplDir,'/') . '/';
			}
		}
		//判断模板路径是否存在  如果不存在要创建,权限是否可写 就需要更改权限
		if (isset($cacheDir)) {
			if ($this->_checkDir($cacheDir)) {
				$this->tplDir = rtrim($cacheDir,'/') . '/';
			}
		}
		//初始化缓存时间
		if (isset($cacheLifeTime)) {
			$thsi->cacheLifeTime = $cacheLifeTime;
		}
	}

	//目录的创建以及权限的处理
	private function _checkDir($path)
	{
		//判断是否存在目录以及是否是目录
		if (!file_exists($path) || !is_dir($path)) {
			 return mkdir($path,0755,true);
		}

		//判断目录的权限是否可读可写
		if (!is_readable($path) || !is_writable($path)) {
			return chmod($path,0755);
		}

		return true;
	}

	//分配变量 主要的目的是将模板中需要处理的代码在php中替换做准备
	public function assign($key,$val)
	{
		$this->vars[$key] = $val;

	}

	//display 显示模板文件
	public function display($file,$isExecute = true ,$uri = null)
	{

	   	//获得模板路径(模板目录路径+模板文件)
	   	$tplFilePath = $this->tplDir.$file;
		//判断文件是否存在
		if (!file_exists($tplFilePath)) {
			exit('模板文件不存在');		}
		//获得编译文件路径(组合一个全新的文件名和路径)
		$cacheFile = md5($file.$uri) . '.php';

		$cacheFilePath  = $this->cacheDir . $cacheFile;

		//检测是否编译过 是否修改过模板文件 如果变编译过 而且在有效期内则不编译
		if (!file_exists($cacheFilePath)) {
			$html = $this->compile($tplFilePath);

		} else {

			//如果修改过模版文件  就需要删除原来的编译文件重新编译
			if (filemtime($tplFilePath) > filemtime($cacheFilePath)) {

				//删除原来的文件
				unlink($cacheFilePath);

				//重新编译
				$html = $this->compile($tplFilePath);

			}

			//文件创建时间+缓存有效期 > time() [当前时间], 没有过期  否则过期
			$isTimeout = (filemtime($tplFilePath) + $this->cacheLifeTime > time()) ? false : true;

			if ($isTimeout) {
				$html = $this->compile($tplFilePath);
			}
		}

		//编译
		if (isset($html)) {
			if (!file_put_contents($cacheFilePath, $html)) {
				exit('编译文件写入失败');
			}
		}

		//执行
		if ($isExecute) {
			extract($this->vars);
			include $cacheFilePath;
		}
	}

	//编译的方法  将html的php代码替换成php代码来执行 并且生成一个缓存
	protected function compile($tplFilePath)
	{
		//将整个文件读入一个字符串
		$html = file_get_contents($tplFilePath);

		//正则替换规则
		$keys = [
			'{if %%}' => '',
            '{else}' => '',
            '{else if %%}' => '',
            '{elseif %%}' => '',
            '{/if}' => '',
            '{$%%}' => '',
            '{foreach %%}' => '',
            '{/foreach}' => '',
            '{for %%}' => '',
            '{/for}' => '',
            '{while %%}' => '',
            '{/while}' => '',
            '{continue}' => '',
            '{break}' => '',
            '{$%% = $%%}' => '',
            '{$%%++}' => '',
            '{$%%--}' => '',
            '{comment}' => ' ' */ ?>',
            '{/*}' => ' '* ?>',
            '{section}' => ' '?>',
			'{{%%(%%)}}' => '',

			'{include %%}' => '',

		];

			//通过遍历 然后一一替换
		foreach ($keys as $key => $value) {
				//正则匹配替换
			$patten = '#' . str_replace('%%', '(.+)', preg_quote($key,'#')) . '#imsU';

			$replace = $value;

			//包含文件处理 include处理方式不一样
			if (stripos($patten, 'include')) {
				// 执行一个正则表达式搜索并且使用一个回调进行替换
				$html = preg_replace_callback($patten, array($this,'parseInclude'), $html);

			} else {

				$html = preg_replace($patten, $replace, $html);
			}

		}
		return $html;

	}

	protected function parseInclude($data)
	{

		$file = str_replace(['\'','"'],'',$data[1]);

		$path = $this->parsePath($file);

		$this->display($file,false);

		return '';
	}

	//处理文件名  将汉字符号等统一设置为32位的加密文件名
	protected function parsePath($file)
	{

		$path = $this->cacheDir . md5($file).'.php';

		return $path;
	}

	//删除缓存文件(递归)
	public function clearCache()
	{
		self::delDir($this->cacheDir);
	}

	//递归删除缓存的文件
	public static function delDir($path)
	{
		$res = opendir($path);

		while($file = readdir($res)){
			if ($file == '.' || $file == '..') {
				continue;
			}

			$newPath = $path.'/'.$file;

			if (is_dir($newPath)) {

				self::delDir($newpath);
			} else {
				unlink($newPath);
			}
		}
	}

}


测试代码:

$tpl = new Tpl();
$tpl->assign('hello','world');
$tpl->assign('chensen','你好森林么么哒');


$tpl->display('index.html');


相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...