您现在的位置是: 首页> PHP>PHP模板引擎实现原理 所属分类:PHP

PHP模板引擎实现原理

初柒先生 2019-09-27 14:36 php】 【模板引擎 253人已围观

简介原理:(1)用户访问PHP页面(2)系统加载模板引擎(3)如果是第一次访问页面模板或者页面模板被修改,模板引擎将对页面模板进行编译处理,从而获得编译后的缓存文件(4)展示页面给用户

原理:

(1)用户访问PHP页面

(2)系统加载模板引擎

(3)如果是第一次访问页面模板或者页面模板被修改,模板引擎将对页面模板进行编译处理,从而获得编译后的缓存文件

(4)展示页面给用户

一个模板引擎,一般由核心类、模板文件、编译文件,三个部分组成。自定义的模板引擎核心类Tpl.class.php,代码如下:

<?php
class Tpl{
	//指定模板目录
	private $template_dir;
	//编译后的目录
	private $compile_dir;
	//读取模板中所有变量的数组
	private $arr_var=array();

	//构造方法
	public function __construct($template_dir="./templates",$compile_dir="./templates_c"){
		$this->template_dir=rtrim($template_dir,"/")."/";
		$this->compile_dir=rtrim($compile_dir,"/")."/";
	}

	//模板中变量分配调用的方法
	public function assign($tpl_var,$value=null){
		$this->arr_var[$tpl_var]=$value;
	}

	//调用模板显示
	public function display($fileName){
		$tplFile=$this->template_dir.$fileName;
		if(!file_exists($tplFile)){
			return false;
		}
		//定义编译合成的文件 加了前缀 和路径 和后缀名.php
		$comFileName=$this->compile_dir."com_".$fileName.".php";
		
		//如果缓存文件不存在则 编译 或者文件修改了也编译
		if(!file_exists($comFileName) || filemtime($comFileName)< filemtime($tplFile)){
			//得到模板文件并替换占位符并得到替换后的文件
			$repContent=$this->tmp_replace(file_get_contents($tplFile));
			//将替换后的文件写入定义的缓存文件中
			file_put_contents($comFileName,$repContent);
		}

		//包含编译后的文件
		include $comFileName;
	}

	//替换模板中的占位符
	private function tmp_replace($content){
		//使用方法:<!--$key-->
		$pattern=array(
			'/\<\!--\s*\$([a-zA-Z]*)\s*--\>/i'
		);
		$replacement=array(
			'<?php echo $this->arr_var["${1}"]; ?>'
		);
		$repContent=preg_replace($pattern,$replacement,$content);
		return $repContent;
	}
}

使用例子:

<?php
	//导入模板引擎类
	include"Tpl.class.php";
	
	//实例化模板引擎类
	$tpl=new Tpl();
	
	//定义变量
	$title="this is title";
	$content="this is content";

	//分配变量
	$tpl->assign("title",$title);
	$tpl->assign("content",$content);
	
	//指定处理的模板
	$tpl->display("tpl.html");
?>

例子下载地址:https://pan.baidu.com/s/13QwSMG9aCL0w6uBBtWpKCg  提取码:trgp 

很赞哦! (3)

初柒先生 2019-09-27 14:36 php】 【模板引擎 253人已围观

站点信息

  • 建站时间:2019-09-04
  • 网站名称:初柒先生
  • 主题模板《今夕何夕》
  • 文章统计:299条
  • 文章评论:490条
  • 统计数据百度统计
  • 微信公众号:初柒先生(chuqi_sir)
  • 微信扫二维码,关注我们吧!
搜索历史:
0.068008s