搜索
首页后端开发php教程PHP 实现简单的模板引擎

模板引擎作为视图层和模型曾分离的一种解决方案。

首先我们新建一个Template.class.php 的文件

<?phpclass Template{		private $arrayConfig = array(		'suffix'      => '.m', 			//设置模板文件		'templateDir' => 'template/', 	//设置模板所在的文件夹		'compileDir'  => 'cache',		'debug'      => false,		//设置编译后存放的目录		'cache_htm'	  =>  true,		//是否需要编译成静态的html文件		'suffix_cache'=> '.htm',		//编译后的文件后缀			'cache_time'  =>2000,			// 多长时间自动更新		'php_turn'    =>false,			//是否支持原生的php代码		'cache_control' => 'control.dat',		);			private $compileTool;		//编译器	public $filename;		//模板文件名称	private $value =array();		//值栈	static private $instance  = null;		public $debug = array();	//调试信息	public function __construct($arrayConfig =array()){	        //返回当前UNIX时间戳和微妙数		$this->debug['begin'] = microtime(true);		$this->arrayConfig =$arrayConfig+$this->arrayConfig;		$this->getPath();		if(!is_dir($this->arrayConfig['templateDir'])){			exit("template isnt not found");		}		if(!is_dir($this->arrayConfig['compileDir'])){						mkdir($this->arrayConfig['compileDir'],0770,true);		}	include("Compile.class.php");		//$this->compileTool = new Compile;	}	/**				路径处理为绝对路径		*/	public function getPath(){		$this->arrayConfig['templateDir'] = strtr(realpath($this->arrayConfig['templateDir']),'\\','/').'/';		$this->arrayConfig['compileDir'] = strtr(realpath($this->arrayConfig['compileDir']),'\\','/').'/';	}		/***				单例模式获取模板的实例	**/	public static function getInstance(){		if(is_null(self::$instance)){			self::$instance = new Template();		}		return self::$instance;	}		public function setConfig($key,$value = null){		if(is_array($key)){			$this->arrayConfig = $key+$this->arrayConfig;		}else{			$this->arrayConfig[$key] = $value;		}	}	public function getConfig($key = null){		if($key){			return $this->arrayConfig[$key];		}else{			return $this->arrayConfig;		}			}		/**		    注入单个变量	**/	public function assign($key,$value){		$this->value[$key] = $value;	}		/**	    注入多个变量	**/	public function assignArray($array){		if(is_array($array)){				foreach($array as $k => $v){					$this->value[$k] = $v;				}						}	}	/***	        获取模板文件的路径		**/		public function path(){		return $this->arrayConfig['templateDir'].$this->filename.$this->arrayConfig['suffix'];	}	/***			是否需要缓存	**/	public function needCache(){		return $this->arrayConfig['cache_htm'];	}		/***				是否需要重新生成缓存文件	**/		public function reCache($file){		$flag = false;		//生成缓存文件		$cacheFile = $this->arrayConfig['compileDir'].md5(@$filename).'.'.'php';		//var_dump($cacheFile);		if($this->arrayConfig['cache_htm']===true){				//设置timeflag (判断当前时间-模板文件上次修改的时间)是否小于设置的缓存时间		//如果小于则返回TRUE					$timeFlag = (time()-@filemtime($cacheFile))<$this->arrayConfig['cache_time']?			true:false;	//1,判断缓存文件是否存在,	//2,缓存文件是否有内容	//3,时间是否在设置的缓存时间之内					if(!is_file($cacheFile)&&filesize($cacheFile)>1&&$timeFlag){				$flag = true;			}else{				$flag = false;			}		}		return $flag;	}	/***		显示模板	**/	public function show($file){		$this->filename =$file;		if(!is_file($this->path())){			exit('找不到相对应的模板');		}		$compileFile = $this->arrayConfig['compileDir'].'/'.md5(@$filename).'.php';		$cacheFile = $this->arrayConfig['compileDir'].md5(@$filename).'.htm';	//	echo $compileFile;		//echo $cacheFile;		if($this->reCache($file)===false){			$this->debug['cached'] = 'false';		//	var_dump($compileFile);			$this->compileTool = new Compile($this->path(),$compileFile,$this->arrayConfig);			if($this->needCache()){			//是否需要缓存				ob_start();			}			//函数从数组中把变量导入到当前的符号表中			extract($this->value,EXTR_OVERWRITE);			//判断 文件是否存在,生成文件的修改时间是否小于模板文件修改时间			if(@is_file($compileFile)||filemtime($compileFile)<filemtime($this->path())){				$this->compileTool->vars = $this->value;				$this->compileTool->compile();				//引入文件				include $compileFile;			}else{				include $compileFile;			}			if($this->needCache()){			//如果需要缓存的话				$message = ob_get_contents();				//则生成缓存文件				file_put_contents($cacheFile,$message);			}					}else{		//如果缓存文件时间小于设定的时间		//直接读取缓存文件			readfile($cacheFile);			//$this->debug['cached'] = true;		}		$this->debug['spend'] = microtime(true) - $this->debug['begin'];		$this->debug['count'] = count($this->value);		$this->debug_info();				/*		var_dump($compileFile);this		var_dump($this->path());		if(!is_file($compileFile)){			mkdir($this->arrayConfig['compileDir']);  //	此处若存在需要判断			$this->compileTool->compile($this->path(),$compileFile);			readfile($compileFile);		}else{			readfile($compileFile);		}		*/	}	/***			debug 调试函数	**/	public function debug_info(){		//$this->arrayConfig['debug']=false;		if($this->arrayConfig['debug']===true){			var_dump($this);			echo "程序运行日期",date("Y-m-d h:i:s")."</br>";			echo "模板解析耗时",$this->debug['spend'],'秒'."</br>";			echo "模板包含标签数目",$this->debug['count']."</br>";			echo "是否使用静态缓存",$this->debug['cached']."</br>";			//echo "模板引擎实例参数",var_dump($this->getConfig());		}	}	/******		清楚缓存的文件			*****/	public function clean($path = null){		if($path = null){			$path = $this->arrayConfig['CompileDir'];			$path = glob($path.'*'.$this->arrayConfig['suffix_cache']);			//glob 函数返回匹配指定的文件夹目录					}else{			$path = $this->arrayConfig['compileDir'].md5($path).'.htm';			foreach((array)$path as $v){			//删除				unlink($v);			}		}	}			}

新建一个 Compile.class.php 翻译模板文件

<?php	class Compile{		private $template;	//待编译的文件		private $content;	//需要替换的文本		private $comfile;		//编译后的 文件		private $left = '{';				private $right = '}';		private $value =array();  // 值栈		private $phpTurn;		private $T_P = 	array();		private $T_R = array();						public function __construct($template,$compileFile,$config){			//echo $template;			//echo $compileFile;			$this->template = $template;			$this->comfile = $compileFile;			$this->content = file_get_contents($template);			if($config['php_turn']===false){				//echo "123";				//$this->T_R[]="";			}			//echo "123";			//正则匹配 {$xxx} 格式			$this->T_P[]="#\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}#";			$this->T_R[]="<?php echo \$this->value['\\1'];?>";		}		public function compile(){			$this->c_var2();			//$this->c_staticFile();			//var_dump($this);			file_put_contents($this->comfile,$this->content);		}		public function c_var2(){		//        将{$xxx} 替换为<?php echo $xxx?>			$this->content = preg_replace($this->T_P,$this->T_R,$this->content);		}		public function c_staticFile(){			$this->content =preg_replace('#\{\!(.*?)\!\}#','<script src =\\1'.'?t='.time().'></script>',$this->content);		}		public function __set($name,$value){			$this->$name = $value;					}		public function __get($name){			return $this->$name;					}	}

新建一个测试文件 test.php

<?phpinclude "Template.class.php";$tpl = Template::getInstance();//$tpl = new Template(array('php_turn'=>false,'debug'=>false));$tpl->assign('data','hello world');$tpl->show('member');//var_dump($tpl->getConfig());

模板文件member.m

<html><head></head><body><h1 id="welcome">welcome</h1></body>{$data}</html>

显示截图

借鉴  php核心技术与最佳实践


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP与Python:了解差异PHP与Python:了解差异Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

php:死亡还是简单地适应?php:死亡还是简单地适应?Apr 11, 2025 am 12:13 AM

PHP不是在消亡,而是在不断适应和进化。1)PHP从1994年起经历多次版本迭代,适应新技术趋势。2)目前广泛应用于电子商务、内容管理系统等领域。3)PHP8引入JIT编译器等功能,提升性能和现代化。4)使用OPcache和遵循PSR-12标准可优化性能和代码质量。

PHP的未来:改编和创新PHP的未来:改编和创新Apr 11, 2025 am 12:01 AM

PHP的未来将通过适应新技术趋势和引入创新特性来实现:1)适应云计算、容器化和微服务架构,支持Docker和Kubernetes;2)引入JIT编译器和枚举类型,提升性能和数据处理效率;3)持续优化性能和推广最佳实践。

您什么时候使用特质与PHP中的抽象类或接口?您什么时候使用特质与PHP中的抽象类或接口?Apr 10, 2025 am 09:39 AM

在PHP中,trait适用于需要方法复用但不适合使用继承的情况。1)trait允许在类中复用方法,避免多重继承复杂性。2)使用trait时需注意方法冲突,可通过insteadof和as关键字解决。3)应避免过度使用trait,保持其单一职责,以优化性能和提高代码可维护性。

什么是依赖性注入容器(DIC),为什么在PHP中使用一个?什么是依赖性注入容器(DIC),为什么在PHP中使用一个?Apr 10, 2025 am 09:38 AM

依赖注入容器(DIC)是一种管理和提供对象依赖关系的工具,用于PHP项目中。DIC的主要好处包括:1.解耦,使组件独立,代码易维护和测试;2.灵活性,易替换或修改依赖关系;3.可测试性,方便注入mock对象进行单元测试。

与常规PHP阵列相比,解释SPL SplfixedArray及其性能特征。与常规PHP阵列相比,解释SPL SplfixedArray及其性能特征。Apr 10, 2025 am 09:37 AM

SplFixedArray在PHP中是一种固定大小的数组,适用于需要高性能和低内存使用量的场景。1)它在创建时需指定大小,避免动态调整带来的开销。2)基于C语言数组,直接操作内存,访问速度快。3)适合大规模数据处理和内存敏感环境,但需谨慎使用,因其大小固定。

PHP如何安全地上载文件?PHP如何安全地上载文件?Apr 10, 2025 am 09:37 AM

PHP通过$\_FILES变量处理文件上传,确保安全性的方法包括:1.检查上传错误,2.验证文件类型和大小,3.防止文件覆盖,4.移动文件到永久存储位置。

什么是无效的合并操作员(??)和无效分配运算符(?? =)?什么是无效的合并操作员(??)和无效分配运算符(?? =)?Apr 10, 2025 am 09:33 AM

JavaScript中处理空值可以使用NullCoalescingOperator(??)和NullCoalescingAssignmentOperator(??=)。1.??返回第一个非null或非undefined的操作数。2.??=将变量赋值为右操作数的值,但前提是该变量为null或undefined。这些操作符简化了代码逻辑,提高了可读性和性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。