当前位置:首页 > PHP教程 > php高级应用 > 列表

php制作简单模版引擎

发布:smiling 来源: PHP粉丝网  添加日期:2021-07-27 10:41:09 浏览: 评论:0 

模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。

PHP模板引擎就是一个PHP类库,使用它可以使PHP代码和HTML代码进行分离,使代码的可读性和维护性得到显著提高,而且这样做的好处是,让美工专心设计HTML前台页面,程序员专心去写PHP业务逻辑,因此,模化引擎很适合公司的Web开发团队使用,使每个人都能发挥其特长

下面我们就来看看如何简单的来实现php的模板引擎

parser.class.php

  1. <?php 
  2.    
  3. /** 
  4.  * 模版解析类 
  5.  */ 
  6. class Parser 
  7. { 
  8.   // 字段,接收模版文件内容 
  9.   private $_tpl; 
  10.      
  11.   // 构造方法,获取模版文件内容 
  12.   public function __construct($_tplFile) 
  13.   { 
  14.     if (! $this->_tpl = file_get_contents($_tplFile)) { 
  15.       exit('ERROR:模版文件读取错误'); 
  16.     } 
  17.   } 
  18.      
  19.   // 解析普通变量 
  20.   private function parvar() 
  21.   { 
  22.     $_patten = '/<!--\s+\{\$([\w]+)\}\s+-->/'; 
  23.     if (preg_match($_patten,$this->_tpl)) { 
  24.       $this->_tpl = preg_replace($_patten, "<?php echo \$this->_vars['$1'];?>",$this->_tpl); 
  25.     } 
  26.   } 
  27.    
  28.   //解析IF语句 
  29.   private function parif(){ 
  30.     $_pattenif = '/<!--\s+\{if\s+\$([\w]+)\}\s+-->/'; 
  31.     $_pattenElse = '/<!--\s+\{else\}\s+-->/'; 
  32.     $_pattenEndif = '/<!--\s+\{\/if\}\s+-->/'; 
  33.     if (preg_match($_pattenif,$this->_tpl)) { 
  34.       if (preg_match($_pattenEndif,$this->_tpl)) { 
  35.         $this->_tpl = preg_replace($_pattenif,"<?php if (\$this->_vars['$1']){?>",$this->_tpl); 
  36.         $this->_tpl = preg_replace($_pattenEndif,"<?php } ?>",$this->_tpl); 
  37.         if (preg_match($_pattenElse,$this->_tpl)) { 
  38.           $this->_tpl = preg_replace($_pattenElse,"<?php }else{?>",$this->_tpl); 
  39.         } 
  40.       }else{ 
  41.       echo 'ERROR:IF语句没有关闭!'; 
  42.       } 
  43.     } 
  44.   } 
  45.    
  46.   //PHP注释解析 
  47.    
  48.   private function parCommon(){ 
  49.     $_pattenCommon = '/<!--\s+\{#\}(.*)\{#\}\s+-->/'; 
  50.     if (preg_match($_pattenCommon,$this->_tpl)) { 
  51.       $this->_tpl = preg_replace($_pattenCommon,"<?php /* $1 */ ?>",$this->_tpl); 
  52.     } 
  53.   } 
  54.      
  55.   //解析foreach语句 
  56.   private function parForeach(){ 
  57.     $_pattenForeach = '/<!--\s+\{foreach\s+\$([\w]+)\(([\w]+),([\w]+)\)\}\s+-->/'; 
  58.     $_pattenForeachEnd = '/<!--\s+\{\/foreach\}\s+-->/'; 
  59.     $_pattenForeachValue = '/<!--\s+\{@([\w]+)\}\s+-->/'; 
  60.     if (preg_match($_pattenForeach,$this->_tpl)) { 
  61.       if (preg_match($_pattenForeachEnd,$this->_tpl)) { 
  62.         $this->_tpl = preg_replace($_pattenForeach, "<?php foreach (\$this->_vars['$1'] as \$$2=>\$$3) {?>", $this->_tpl); 
  63.         $this->_tpl = preg_replace($_pattenForeachEnd, "<?php }?>", $this->_tpl); 
  64.         if (preg_match($_pattenForeachValue, $this->_tpl)) { 
  65.           $this->_tpl = preg_replace($_pattenForeachValue,"<?php echo \$$1;?>",$this->_tpl); 
  66.         } 
  67.       }else{ 
  68.       echo 'ERROR:Foreach语句没有关闭!';   
  69.       } 
  70.     } 
  71.   } 
  72.    
  73.   //解析include方法 
  74.   private function parInclude(){ 
  75.     $_pattenInclude = '/<!--\s+\{include\s+file=\"([\w\.\-]+)\"\}\s+-->/'; 
  76.     if (preg_match($_pattenInclude,$this->_tpl,$_file,$_file)) { 
  77.       if (!file_exists($_file[1])||emptyempty($_file)) { 
  78.         echo 'ERROR:包含文件出错!'; 
  79.       } 
  80.       $this->_tpl = preg_replace($_pattenInclude,"<?php include '$1';?>",$this->_tpl); 
  81.     } 
  82.   } 
  83.    
  84.   //解析系统变量方法 
  85.   private function parConfig(){ 
  86.     $_pattenConfig = '/<!--\s+\{([\w]+)\}\s+-->/'; 
  87.     if (preg_match($_pattenConfig,$this->_tpl)) { 
  88.       $this->_tpl = preg_replace($_pattenConfig,"<?php echo \$this->_config['$1'];?>",$this->_tpl); 
  89.     } 
  90.   } 
  91.   // 对外公共方法 
  92.   public function compile($_path) 
  93.   { 
  94.     // 解析模版文件 
  95.     $this->parvar(); 
  96.     $this->parif(); 
  97.     $this->parForeach(); 
  98.     $this->parInclude(); 
  99.     $this->parCommon(); 
  100.     $this->parConfig(); 
  101.     // 生成编译文件 
  102.     if (! file_put_contents($_path, $this->_tpl)) { 
  103.       exit('ERROR:编译文件生成错误!'); 
  104.     } 
  105.   } 
  106. } 
  107. ?> 

Templates.class.php

  1. <?php 
  2.    
  3. /** 
  4.  * 模版类 
  5.  */ 
  6. class Templates 
  7. { 
  8.   //注入变量 
  9.   private $_vars = array(); 
  10.   //保存系统变量数组字段 
  11.   private $_config = array(); 
  12.   //创建一个构造方法,来检测各个目录是否存在 
  13.   public function __construct() 
  14.   { 
  15.     if (! is_dir(TPL_DIR) || ! is_dir(TPL_C_DIR) || ! is_dir(CACHE) || !is_dir(CONFIG)) { 
  16.       echo 'ERROR:模版目录或编译目录,缓存目录不存在!自动创建!'."<br />"; 
  17.       if (!is_dir(TPL_DIR)) { 
  18.         mkdir(TPL_DIR); 
  19.         echo '模版目录'.TPL_DIR.'建立'."<br />"; 
  20.       } 
  21.       if (!is_dir(TPL_C_DIR)) { 
  22.         mkdir(TPL_C_DIR); 
  23.         echo '编译目录'.TPL_C_DIR.'建立'."<br />"; 
  24.       } 
  25.       if (!is_dir(CACHE)) { 
  26.         mkdir(CACHE); 
  27.         echo '缓存目录'.CACHE.'建立'."<br />"; 
  28.       } 
  29.       if (!is_dir(CONFIG)) { 
  30.         mkdir(CONFIG); 
  31.         echo '缓存目录'.CONFIG.'建立'."<br />"; 
  32.       } 
  33.       exit(); 
  34.     } 
  35.     //保存系统变量 
  36.     $_sxe = simplexml_load_file(CONFIG.'/config.xml'); 
  37.     $_tagLib = $_sxe->xpath('/root/taglib'); 
  38.     foreach ($_tagLib as $_tag) { 
  39.       $this->_config["$_tag->name"] = $_tag->value; 
  40.     } 
  41.   } 
  42.    
  43.   //assign()方法,用于注入变量 
  44.   public function assign($_var,$_value){ 
  45.     //$_var用于同步模版里的变量名 
  46.     //$_value表示值 
  47.     if (isset($_var)&&!emptyempty($_var)) { 
  48.       $this->_vars[$_var] = $_value; 
  49.     }else{ 
  50.       exit('ERROR:设置模版变量!'); 
  51.     } 
  52.    
  53.   } 
  54.    
  55.   //display()方法 
  56.   public function display($_file) 
  57.   { 
  58.     $_tplFile = TPL_DIR . $_file; 
  59.     // 判断文件是否存在 
  60.     if (! file_exists($_tplFile)) { 
  61.       echo 'ERROR:模版文件不存在!自动创建Index.tpl模版文件!'; 
  62.       file_put_contents($_tplFile,'Index'); 
  63.       exit(); 
  64.     } 
  65.    
  66.     //生成编译文件 
  67.     $_path = TPL_C_DIR.md5($_file).'-'.$_file.'.php'; 
  68.     //缓存文件 
  69.     $_cacheFile = CACHE.md5($_file).'-'.$_file.'.html'; 
  70.     //当第二次运行相同文件,直接载入缓存文件 
  71.     if (IS_CACHE) { 
  72.       //判断缓存文件和编译文件都存在 
  73.       if (file_exists($_cacheFile)&&file_exists($_path)) { 
  74.         //判断模版文件是否修改过 
  75.         if (filemtime($_path)>=filemtime($_tplFile)&&filemtime($_cacheFile)>=filemtime($_path)) { 
  76.           include $_cacheFile; 
  77.           echo '<!--cache-->'; 
  78.           return; 
  79.         } 
  80.       } 
  81.     } 
  82.     //当编译文件不存在或者文件发生改变则重新生成 
  83.     if (!file_exists($_path)||filemtime($_path)<filemtime($_tplFile)) { 
  84.       require ROOT_PATH.'/Class/parser.class.php'; 
  85.       //构造方法是传入模版文件地址 
  86.       $_parser = new Parser($_tplFile); 
  87.       //传入编译文件地址 
  88.       $_parser->compile($_path); 
  89.     } 
  90.     //载入编译文件 
  91.     include $_path; 
  92.     if (IS_CACHE) { 
  93.       //获取缓冲区数据 
  94.       file_put_contents($_cacheFile,ob_get_contents()); 
  95.       //清楚缓冲区 
  96.       ob_end_clean(); 
  97.       //载入缓存文件 
  98.       include $_cacheFile; 
  99.     } 
  100.   } 
  101. } 
  102. ?> 

templates.php

  1. <?php 
  2. //设置字符编码UTF-8 
  3. header('Content-Type:text/html;charset=utf-8'); 
  4.    
  5. //网站根目录 
  6. define('ROOT_PATH',dirname(__FILE__)); 
  7.    
  8. //存放模版文件夹 
  9. define('TPL_DIR',ROOT_PATH.'/Templates/'); 
  10.    
  11. //编译文件夹 
  12. define('TPL_C_DIR',ROOT_PATH.'/Templates_c/'); 
  13.    
  14. //缓存文件夹 
  15. define('CACHE',ROOT_PATH.'/Cache/'); 
  16.    
  17. //系统变量配置目录 
  18. define('CONFIG',ROOT_PATH.'/Config/'); 
  19.    
  20. //是否开启缓冲区 
  21. define('IS_CACHE',false);//false 
  22.    
  23. //判断是否需要开启 
  24. IS_CACHE ? ob_start() : null; 
  25.    
  26. //引入模版类 
  27. require ROOT_PATH.'/Class/Templates.class.php'; 
  28.    
  29. //实例化模版类 
  30. $_tpl=new Templates(); 
  31.    
  32. $_tpl->display('index.tpl'); 
  33. ?> 

templates/index.tpl

  1. <!DOCTYPE html> 
  2. <html lang="zn-cn"> 
  3. <head> 
  4.   <meta charset="UTF-8"> 
  5.   <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> 
  6.   <meta name="description" content=""> 
  7.   <meta name="keywords" content=""> 
  8.   <meta name="author" content=""> 
  9.   <meta name="author" content=""> 
  10.   <title><!-- {WebName} --></title> 
  11.   <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> 
  12.   <link rel="stylesheet" type="text/css" href="css/style.css"> 
  13.   </head> 
  14. <body> 
  15.    
  16. <!-- {#}php注释{#} --> 
  17. <!-- {if $a} --> 
  18. 123 
  19. <!-- {else} --> 
  20. 321 
  21. <!-- {/if} --> 
  22. <br /> 
  23. <!-- {foreach $array(key,value)} --> 
  24.   <!-- {@key} -->...<!-- {@value} --><br /> 
  25. <!-- {/foreach} --> 
  26. 系统变量<!-- {WebName} --><br /> 
  27. 普通变量<!-- {$name} --><br /> 
  28.  
  29.   <script src="/js/jquery-2.2.1.min.js" type="text/javascript"></script> 
  30.   <script src="/js/bootstrap.min.js" type="text/javascript"></script> 
  31.   <script type="text/javascript"> 
  32.   </script> 
  33. </body> 
  34. </html> 

config/config.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <root> 
  3.   <taglib> 
  4.     <name>WebName</name> 
  5.     <value>XXX网站</value> 
  6.   </taglib> 
  7. </root>

Tags: php模版引擎

分享到: