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

PHP模版引擎原理、定义与用法实例

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-14 12:38:46 浏览: 评论:0 

这篇文章主要介绍了PHP模版引擎原理、定义与用法,结合实例形式分析了php模板引擎相关的模板编译、缓存处理、变量替换等操作技巧,需要的朋友可以参考下。

本文实例讲述了PHP模版引擎原理、定义与用法,分享给大家供大家参考,具体如下:

template存放模版源文件

模版编译工具类

Compline.class.php

  1. <?php 
  2. /** 
  3. * 模板编译工具类 
  4. */ 
  5. class Compile 
  6. { 
  7.   private $template;     //带编译文件 
  8.   private $content;      //需要替换的文本 
  9.   private $comfile;      //编译后的文件 
  10.   private $left = '{';     //左界定符 
  11.   private $right = '}';    //右界定符 
  12.   private $value = array();   //值栈 
  13.   private $php_turn; 
  14.   private $T_P = array(); 
  15.   private $T_R = array(); 
  16.   public function __construct($template, $compileFile, $config) 
  17.   { 
  18.    $this->template = $template; 
  19.    $this->comfile = $compileFile; 
  20.    $this->content = file_get_contents($template); 
  21.    if($config['php_turn'] === false) 
  22.    { 
  23.      $this->T_P[] = "/<\?(=|php|)(.+?)\?>/is"; 
  24.      $this->T_R[] = "&lt;? \\1\\2? &gt"; 
  25.    } 
  26.    //{$var} 
  27.    $this->T_P[] = "/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/"; 
  28.    //{foreach $b}或者{loop $b} 
  29.    $this->T_P[] = "/\{(loop|foreach) \\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/i"; 
  30.    //{[K|V]} 
  31.    $this->T_P[] = "/\{([K|V])\}/"; 
  32.    //{/foreach}或者{\loop}或者{\if} 
  33.    $this->T_P[] = "/\{\/(loop|foreach|if)}/i"; 
  34.    //{if (condition)} 
  35.    $this->T_P[] = "/\{if (.* ?)\}/i"; 
  36.    //{(else if | elseif)} 
  37.    $this->T_P[] = "/\{(else if|elseif) (.* ?)\}/i"; 
  38.    //{else} 
  39.    $this->T_P[] = "/\{else\}/i"; 
  40.    //{#...# 或者 *...#,注释} 
  41.    $this->T_P[] = "/\{(\#|\*)(.* ?)(\#|\*)\}/"; 
  42.    $this->T_R[] = "<?php echo \$this->value['\\1']; ?>"; 
  43.    $this->T_R[] = "<?php foreach ((array)\$this->value['\\2'] as \$K => \$V) { ?>"; 
  44.    $this->T_R[] = "<?php echo \$\\1; ?>"; 
  45.    $this->T_R[] = "<?php } ?>"; 
  46.    $this->T_R[] = "<?php if (\\1) { ?>"; 
  47.    $this->T_R[] = "<?php }else if (\\2) { ?>"; 
  48.    $this->T_R[] = "<?php }else{ ?>"; 
  49.    $this->T_R[] = ""; 
  50.   } 
  51.   public function compile() 
  52.   { 
  53.    $this->c_all(); 
  54.    $this->c_staticFile(); 
  55.    file_put_contents($this->comfile, $this->content); 
  56.   } 
  57.   public function c_all() 
  58.   { 
  59.    $this->content = preg_replace($this->T_P, $this->T_R, $this->content); 
  60.   } 
  61.   /** 
  62.   * 加入对JavaScript文件的解析 
  63.   * @return [type] [description] 
  64.   */ 
  65.   public function c_staticFile() 
  66.   { 
  67.    $this->content = preg_replace('/\{\!(.* ?)\!\}/', '<script src=\\1'.'?t='.time().'></script>', $this->content); 
  68.   } 
  69.   public function __set($name, $value) 
  70.   { 
  71.    $this->$name = $value; 
  72.   } 
  73.   public function __get($name) 
  74.   { 
  75.    if(isset($this->$name)) 
  76.    { 
  77.      return $this->$name; 
  78.    } 
  79.    else 
  80.    { 
  81.      return null; 
  82.    } 
  83.   } 
  84. } 

Template.class.php

  1. <?php 
  2. /** 
  3. * Template 
  4. */ 
  5. class Template 
  6. { 
  7.   private $arrayConfig = array( 
  8.    'suffix'   => '.tpl',  //模板的后缀 
  9.    'templateDir' => 'template/', //模板所在的文件夹 
  10.    'compileDir'  => 'cache/',  //编译后存放的目录 
  11.    'cache_html'  => true,   //是否需要编译成静态的html文件 
  12.    'suffix_cache' => '.html',  //设置编译文件的后缀 
  13.    'cache_time'  => 7200,   //设置多长时间自动更新 
  14.    'php_turn'  => true,   //设置是否支持php原生代码 
  15.    'debug'     => false, 
  16.    ); 
  17.   public $file;         //模板文件名,不带路径 
  18.   public $debug = array();     //调试信息 
  19.   private $value = array();    //值栈 
  20.   private $compileTool;      //编译器 
  21.   private $controlData = array(); 
  22.   static private $instance = null;  //模板类对象 
  23.   public function __construct($arrayConfig = array()) 
  24.   { 
  25.    $this->debug['begin'] = microtime(true); 
  26.    $this->arrayConfig = array_merge($this->arrayConfig, $arrayConfig); 
  27.    $this->getPath(); 
  28.    if(!is_dir($this->arrayConfig['templateDir'])) 
  29.    { 
  30.      exit("template dir isn't found!"); 
  31.    } 
  32.    if(!is_dir($this->arrayConfig['compileDir'])) 
  33.    { 
  34.      if(strtoupper(substr(PHP_OS,0,3)) === 'WIN') 
  35.      { 
  36.       mkdir($this->arrayConfig['compileDir']); 
  37.      } 
  38.      else 
  39.      { 
  40.       mkdir($this->arrayConfig['compileDir'], 0770, true); 
  41.      } 
  42.    } 
  43.    include('Compile.class.php'); 
  44.   } 
  45.   public function getPath() 
  46.   { 
  47.    $this->arrayConfig['templateDir'] = strstr(realpath($this->arrayConfig['templateDir']), '\\', '/').'/'; 
  48.    $this->arrayConfig['compileDir'] = strstr(realpath($this->arrayConfig['compileDir'])), '\\', '/').'/'; 
  49.   } 
  50.   /** 
  51.   * 取得模板引擎的实例 
  52.   */ 
  53.   public static function getInstance() 
  54.   { 
  55.    if(is_null(self::$instance)) 
  56.    { 
  57.      self::$instance = new Template(); 
  58.    } 
  59.    return self::$instance; 
  60.   } 
  61.   /** 
  62.   * 单独设置引擎参数 
  63.   * 也支持一次性设置多个参数 
  64.   */ 
  65.   public function setConfig($key, $value = null) 
  66.   { 
  67.    if(is_array($key)) 
  68.    { 
  69.      $this->arrayConfig = $key + $this->arrayConfig; 
  70.    } 
  71.    else 
  72.    { 
  73.      $this->arrayConfig[$key] = $value; 
  74.    } 
  75.   } 
  76.   /** 
  77.   * 获取当前模板引擎配置,仅供调试使用 
  78.   */ 
  79.   public function getConfig($key = null) 
  80.   { 
  81.    if($key && array_key_exists($key, $this->arrayConfig)) 
  82.    { 
  83.      return $this->arrayConfig[$key]; 
  84.    } 
  85.    else 
  86.    { 
  87.      return $this->arrayConfig; 
  88.    } 
  89.   } 
  90.   /** 
  91.   * 注入单个变量 
  92.   */ 
  93.   public function assign($key, $value) 
  94.   { 
  95.    $this->value[$key] = $value; 
  96.   } 
  97.   /** 
  98.   * 注入数组变量 
  99.   */ 
  100.   public function assignArray($array) 
  101.   { 
  102.    if(is_array($array)) 
  103.    { 
  104.      foreach ($array as $k => $v) { 
  105.       $this->value[$k] = $v; 
  106.      } 
  107.    } 
  108.   } 
  109.   /** 
  110.   * 获取模板的位置 
  111.   * @return [type] [description] 
  112.   */ 
  113.   public function path() 
  114.   { 
  115.    return $this->arrayConfig['templateDir'].$this->file.$this->arrayConfig['suffix']; 
  116.   } 
  117.   /** 
  118.   * 判断配置文件是否要求缓存 
  119.   */ 
  120.   public function needCache() 
  121.   { 
  122.    return $this->arrayConfig['cache_html']; 
  123.   } 
  124.   /** 
  125.   * 判断是否需要缓存 
  126.   */ 
  127.   public function reCache($file) 
  128.   { 
  129.    $flag = false; 
  130.    $cacheFile = $this->arrayConfig['compileDir'].md5($file).$this->arrayConfig['suffix_cache']; 
  131.    if($this->arrayConfig['cache_html'] === true) 
  132.    { 
  133.      //需要缓存 
  134.      $timeFlag = (time() - @filemtime($cacheFile)) < $this->arrayConfig['cache_time'] ? true : false; 
  135.      if(is_file($cacheFile) && filesize($cacheFile) > 1 && $timeFlag) 
  136.      { 
  137.       //缓存存在且未过期 
  138.       $flag = true; 
  139.      } 
  140.      else 
  141.      { 
  142.       $flag = false; 
  143.      } 
  144.    } 
  145.    return $flag; 
  146.   } 
  147.   /** 
  148.   * 展示模板 
  149.   */ 
  150.   public function show($file) 
  151.   { 
  152.    $this->file = $file; 
  153.    if(!is_file($this->path())) 
  154.    { 
  155.      exit('找不到对应的模板'); 
  156.    } 
  157.    $compileFile = $this->arrayConfig['compileDir'].md5($file).'.php'; 
  158.    $cacheFile = $this->arrayConfig['compileDir'].md5($file).$this->arrayConfig['suffix_cache']; 
  159.    if($this->reCache($file) === false) 
  160.    { 
  161.      //如果需要缓存 
  162.      $this->debug['cached'] = 'false'; 
  163.      $this->compileTool = new Compile($this->path(), $compileFile, $this->arrayConfig); 
  164.      if($this->needCache()) 
  165.      { 
  166.       ob_start(); 
  167.      } 
  168.      extract($this->value, EXTR_OVERWRITE); 
  169.      if(!is_file($compileFile) || fileatime($compileFile) < filemtime($this->path())) 
  170.      { 
  171.       $this->compileTool->value = $this->value; 
  172.       $this->compileTool->compile(); 
  173.       include $compileFile; 
  174.      } 
  175.      else 
  176.      { 
  177.       include $compileFile; 
  178.      } 
  179.      if($this->needCache()) 
  180.      { 
  181.       $message = ob_get_contents(); 
  182.       file_put_contents($cacheFile, $message); 
  183.      } 
  184.    } 
  185.    else 
  186.    { 
  187.      readfile($cacheFile); 
  188.      $this->debug['cached'] = 'true'; 
  189.    } 
  190.    $this->debug['spend'] = microtime(true) - $this->debug['begin']; 
  191.    $this->debug['count'] = count($this->value); 
  192.    $this->debug_info(); 
  193.   } 
  194.   public function debug_info() 
  195.   { 
  196.    if($this->arrayConfig['debug'] === true) 
  197.    { 
  198.      echo "<br/>", '-------------------- debug_info--------------', "<br/>"; 
  199.      echo '程序运行日期:', date("Y-m-d h:i:s"), "<br/>"; 
  200.      echo '模板解析耗时:', $this->debug['spend'], '秒', "<br/>"; 
  201.      echo '模板包含标签数目:', $this->debug['count'], "<br/>"; 
  202.      echo '是否使用静态缓存:', $this->debug['cached'], "<br/>"; 
  203.      echo '模板引擎实例参数:', var_dump($this->getConfig()); 
  204.    } 
  205.   } 
  206.   /** 
  207.   * 清楚缓存的html文件 
  208.   * @return [type] [description] 
  209.   */ 
  210.   public function clean() 
  211.   { 
  212.    if($path === null) 
  213.    { 
  214.      $path = $this->arrayConfig['compileDir']; 
  215.      $path = glob($path.'* '.$this->arrayConfig['suffix_cache']); 
  216.    } 
  217.    else 
  218.    { 
  219.      $path = $this->arrayConfig['compileDir'].md5($path).$this->arrayConfig['suffix_cache']; 
  220.    } 
  221.    foreach ((array)$path as $v) { 
  222.      unlink($v); 
  223.    } 
  224.   } 
  225. } 

test.php

  1. <?php 
  2. include 'Template.class.php'; 
  3. $tpl = new Template(array('debug' => true)); 
  4. $tpl->assign('data', 'hello world'); 
  5. $tpl->assign('person', 'htGod'); 
  6. $tpl->assign('data1', 3); 
  7. $arr = array(1,2,3,4,'5',6); 
  8. $tpl->assign('b', $arr); 
  9. $tpl->show('member');

Tags: PHP模版引擎 PHP模版定义

分享到: