php tpl模板引擎定义与使用示例


Posted in PHP onAugust 09, 2019

本文实例讲述了php tpl模板引擎定义与使用。分享给大家供大家参考,具体如下:

tpl.php

<?php
namespace tpl;
/**
* Class Tpl
*/
class Tpl
{
  protected $view_dir;//模板文件
  protected $cache_dir;//缓存文件
  protected $lifetime;//过期时间
  protected $vars = [];//存放显示变量的数组
   /**
   * Tpl constructor.
   * @param string $view_dir
   * @param string $cache_dir
   * @param string $lifetime
   */
  public function __construct($view_dir='', $cache_dir='', $lifetime='')
  {
    //如果模板文件不为空,则设置,为空则为默认值
    if (!empty($view_dir)) {
      if ($this->check_dir($view_dir)) {
        $this->view_dir = $view_dir;
      }
    }
    //如果缓存文件不为空,则设置,为空时为默认值
    if (!empty($cache_dir)) {
      if ($this->check_dir($cache_dir)) {
        $this->cache_dir = $cache_dir;
      }
    }
    //如果过期时间不为空,则设置,为空时为默认值
    if (!empty($lifetime)) {
      $this->lifetime = $lifetime;
    }
  }
   /**
   * 对外公开的方法
   * @param string $name
   * @param string $value
   */
  public function assign($name, $value)
  {
    $this->vars[$name] = $value;//将传入的参数以键值对存入数组中
  }
   /**
   * 测试文件
   * @param $dir_path
   * @return bool
   */
  protected function check_dir($dir_path)
  {
    //如果文件不存在或不是文件夹,则创建
    if (!file_exists($dir_path) || !is_dir($dir_path)) {
      return mkdir($dir_path, 0777, true);
    }
    //如果文件不可读或不可写,则设置模式
    if (!is_writable($dir_path) || !is_readable($dir_path)) {
      return chmod($dir_path, 0777);
    }
    return true;
  }
   /**
   * 展示方法
   * @param $view_name
   * @param bool $isInclude
   * @param null $uri
   */
  public function display($view_name, $isInclude=true, $uri=null)
  {
    //通过传入的文件名,得到模板文件路径
    $view_path = rtrim($this->view_dir, '/') . '/' . $view_name;
    //判断路径是否存在
    if (!file_exists($view_path)) {
      die('文件不存在');
    }
    //通过传入的文件名得到缓存文件名
    $cache_name = md5($view_name . $uri) . '.php';
    //缓过缓存文件名得到缓存路径
    $cache_path = rtrim($this->cache_dir, '/') . '/' .$cache_name;
    //判断缓存文件是否存在,如果不存在,重新生成
    if (!file_exists($cache_path)) {
      $php = $this->compile($view_path);//解析模板文件
      file_put_contents($cache_path, $php);//缓存文件重新生成
    } else {
      //如果缓存文件存在,判断是否过期,判断模板文件是否被修改
      $is_time_out = (filectime($cache_path) + $this->lifetime) > time() ? false : true;
      $is_change = filemtime($view_path) > filemtime($cache_path) ? true : false;
      //如果缓存文件过期或模板文件被修改,重新生成缓存文件
      if ($is_time_out || $is_change) {
        $php = $this->compile($view_path);
        file_put_contents($cache_path, $php);
      }
    }
    if ($isInclude) {
      extract($this->vars);//解析传入变量的数组
      include $cache_path;//展示缓存
    }
  }
   /**
   * 正则解析模板文件
   * @param string $file_name
   * @return mixed|string
   */
  protected function compile($file_name)
  {
    $html = file_get_contents($file_name);//获取模板文件
    //正则转换数组
    $array = [
      '{$%%}' => '<?=$\1?>',
      '{foreach %%}' => '<?php foreach (\1): ?>',
      '{/foreach}' => '<?php endforeach ?>',
      '{include %%}' => '',
      '{if %%}' => '<?php if (\1): ?>',
      '{/if}' => '<?php endif ?>',
      '{for %%}' => '<?php for (\1): ?>',
      '{/for}' => '<?php endfor ?>',
      '{switch %%}' => '<?php switch (\1) ?>',
      '{/switch}' => '<?php endswitch ?>'
    ];
    //遍历数组,生成正则表达式
    foreach ($array AS $key=>$value) {
      //正则表达式,
      $pattern = '#' . str_replace('%%', '(.+?)' , preg_quote($key, '#')) . '#';
      if (strstr($pattern, 'include')) {
        $html = preg_replace_callback($pattern, [$this, 'parseInclude'], $html);
      } else {
        $html = preg_replace($pattern, $value, $html);
      }
    }
    return $html;
  }
   /**
   * 处理include表达式
   * @param array $data
   * @return string
   */
  protected function parseInclude($data)
  {
    $file_name = trim($data[1], '\'"');
    $this->display($file_name, false);
    $cache_name = md5($file_name) . '.php';
    $cache_path = rtrim($this->cache_dir, '/') . '/' . $cache_name;
    return '<?php include "'.$cache_path.'" ?>';
  }
}

user_tpl,,,,从数据库中取值,作为参数传到模板文件,再解析模板文件

<?php
include './sql/pdo.sql.php';
include 'tpl.php';
 $tpl = new tpl\Tpl('./view/', './cache/', 3000);
$link = new pdo_sql();
$dat = ['menu_name', 'menu_url'];
$res = $link->table('blog_menu')->field($dat)->order('id ASC')->select();
$tpl->assign('menu', $res);
$tpl->display('index.html');

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
PHP5 面向对象程序设计
Feb 13 PHP
巧用php中的array_filter()函数去掉多维空值的代码分享
Sep 07 PHP
php学习笔记之面向对象编程
Dec 29 PHP
PHP正则提取不包含指定网址的图片地址的例子
Apr 21 PHP
php计算两个日期时间差(返回年、月、日)
Jun 19 PHP
Destoon实现多表查询示例
Aug 21 PHP
php+ajax实时输入自动搜索匹配的方法
Dec 26 PHP
php实现读取内存顺序号
Mar 29 PHP
thinkphp框架实现删除和批量删除
Jun 29 PHP
Yii2实现多域名跨域同步登录退出
Feb 04 PHP
PHP数据库操作二:memcache用法分析
Aug 16 PHP
使用PHP连接数据库_实现用户数据的增删改查的整体操作示例
Sep 01 PHP
php函数式编程简单示例
Aug 08 #PHP
因str_replace导致的注入问题总结
Aug 08 #PHP
PHP goto语句用法实例
Aug 06 #PHP
Laravel 6 将新增为指定队列任务设置中间件的功能
Aug 06 #PHP
Yii框架核心组件类实例详解
Aug 06 #PHP
PHP使用Session实现上传进度功能详解
Aug 06 #PHP
PHP使用ajax的post方式下载excel文件简单示例
Aug 06 #PHP
You might like
php递归遍历多维数组的方法
2015/04/18 PHP
PHP中include/require/include_once/require_once使用心得
2016/08/28 PHP
ie和firefox中img对象区别的困惑
2006/12/27 Javascript
javascript css styleFloat和cssFloat
2010/03/15 Javascript
Array.prototype.slice 使用扩展
2010/06/09 Javascript
加载jQuery后$冲突的解决办法
2010/07/09 Javascript
js日期相关函数总结分享
2013/10/15 Javascript
js 获取、清空input type=&quot;file&quot;的值示例代码
2014/02/19 Javascript
js函数名与form表单元素同名冲突的问题
2014/03/07 Javascript
教你如何使用PHP输出中文JSON字符串
2014/05/22 Javascript
jQuery实现跨域iframe接口方法调用
2015/03/14 Javascript
JavaScript三元运算符的多种使用技巧
2015/04/16 Javascript
javascript实现根据3原色制作颜色选择器的方法
2015/07/17 Javascript
jQuery基于ajax实现页面加载后检查用户登录状态的方法
2017/02/10 Javascript
jQuery选择器之属性筛选选择器用法详解
2017/09/19 jQuery
原生JS实现$.param() 函数的方法
2018/08/10 Javascript
vue.js2.0 实现better-scroll的滚动效果实例详解
2018/08/13 Javascript
利用chrome浏览器进行js调试并找出元素绑定的点击事件详解
2021/01/30 Javascript
vue-cli配置flexible过程详解
2019/07/04 Javascript
微信小程序防止多次点击跳转(函数节流)
2019/09/19 Javascript
解决js中的setInterval清空定时器不管用问题
2020/11/17 Javascript
javascript实现时钟动画
2020/12/03 Javascript
Python中反射和描述器总结
2018/09/23 Python
解决python字典对值(值为列表)赋值出现重复的问题
2019/01/20 Python
使用python PIL库实现简单验证码的去噪方法步骤
2019/05/10 Python
python3 selenium自动化 frame表单嵌套的切换方法
2019/08/23 Python
Python+Selenium随机生成手机验证码并检查页面上是否弹出重复手机号码提示框
2020/09/21 Python
浅析python连接数据库的重要事项
2021/02/22 Python
html5 css3网站菜单实现代码
2013/12/23 HTML / CSS
介绍一下Prototype的$()函数,$F()函数,$A()函数都是什么作用?
2014/03/05 面试题
乡镇计划生育工作汇报
2014/10/28 职场文书
幼儿园教师读书笔记
2015/06/29 职场文书
先进基层党组织主要事迹材料
2015/11/03 职场文书
Django开发RESTful API实现增删改查(入门级)
2021/05/10 Python
CSS 使用 resize 实现图片拖拽切换预览功能(强大功能)
2021/08/23 HTML / CSS
Golang 实现 WebSockets 之创建 WebSockets
2022/04/24 Golang