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');


相关内容

热门资讯

德国总理:美国正在被伊朗羞辱 德国之声4月27日报道,德国总理默茨在访问一所学校时表示,在当前的持续冲突中,伊朗领导层正试图羞辱美...
理响中国|“长”歌以行,风云激... 光阴如梭,东方潮阔。这里是中国的长三角,世界的长三角。无论过去、现在还是未来,这片土地都因时代而生,...
白宫:特朗普及其国安团队开会讨... 新华社华盛顿4月27日电 美国白宫新闻秘书莱维特27日在记者会上证实,总统特朗普及其国家安全团队当天...
人民日报刊文:日本放开杀伤性武... 日本放开杀伤性武器出口推高地缘冲突风险(国际论坛)常思纯《人民日报》(2026年04月28日 第 0...
医疗保障法草案二审:明确生育保... 满足多样化健康保障需求本报记者 彭 波4月27日,医疗保障法草案二审稿提请十四届全国人大常委会第二十...
天津一景区发生自转旋翼机事故1... 澎湃新闻记者 吕新文中国民用航空华北地区管理局4月22日公布《豪客通航“10•1”天津长芦汉盐旅游区...
卡塔尔埃米尔与美国总统特朗普通... 当地时间24日,卡塔尔埃米尔塔米姆与美国总统特朗普通电话,重点就中东地区局势以及伊朗与美国谈判问题交...
男子30年前被扣押2859克黄... 澎湃新闻记者 王鑫家住辽宁省大连市的潘永嘉近日向澎湃新闻反映称,三十年前,他在大连周水子机场被盖州市...
商务部:取消反制欧盟两家金融机... 中华人民共和国商务部令二〇二六年 第1号鉴于欧盟已取消对中国两家金融机构的制裁措施,现公布《关于取消...
过去24小时共有5艘船只通过霍... 总台记者当地时间24日获悉,过去24小时内,共有5艘船只通过霍尔木兹海峡,其中包括一艘伊朗油轮。(总...