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 相关文章推荐
PHP Ajax实现页面无刷新发表评论
Jan 02 PHP
PHP XML备份Mysql数据库
May 27 PHP
php压缩多个CSS为一个css的代码并缓存
Apr 21 PHP
PHP操作文件类的函数代码(文件和文件夹创建,复制,移动和删除)
Nov 10 PHP
php简单浏览目录内容的实现代码
Jun 07 PHP
smarty模板局部缓存方法使用示例
Jun 17 PHP
PHP中require和include路径问题详解
Dec 25 PHP
PHP简单实现二维数组赋值与遍历功能示例
Oct 19 PHP
PDO::errorCode讲解
Jan 28 PHP
thinkphp框架类库扩展操作示例
Nov 26 PHP
Laravel 集成微信用户登录和绑定的实现
Dec 27 PHP
PHP pthreads v3在centos7平台下的安装与配置操作方法
Feb 21 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
剧场版动画《PSYCHO-PASS 3 FIRST INSPECTOR》3月27日日本上映!
2020/03/06 日漫
php preg_filter执行一个正则表达式搜索和替换
2012/02/27 PHP
PHP实现的下载远程图片自定义函数分享
2015/01/28 PHP
php 流程控制switch的简单实例
2016/06/07 PHP
PHP实现普通hash分布式算法简单示例
2018/08/06 PHP
jquery attr 设定src中含有&amp;(宏)符号问题的解决方法
2011/07/26 Javascript
jQuery编辑器KindEditor4.1.4代码高亮显示设置教程
2013/03/01 Javascript
JS定义回车事件(实现代码)
2013/07/08 Javascript
jquery实现带单选按钮的表格行选中时高亮显示
2013/08/01 Javascript
可编辑下拉框的2种实现方式
2014/06/13 Javascript
jquery实现表格本地排序的方法
2015/03/11 Javascript
提高jQuery性能优化的技巧
2015/08/03 Javascript
快速学习AngularJs HTTP响应拦截器
2015/12/31 Javascript
jquery使用Cookie和JSON记录用户最近浏览历史
2016/04/19 Javascript
JS、jQuery中select的用法详解
2016/04/21 Javascript
javascript截图 jQuery插件imgAreaSelect使用详解
2016/05/04 Javascript
JS中作用域和变量提升(hoisting)的深入理解
2016/10/31 Javascript
基于canvas的二维码邀请函生成插件
2017/02/14 Javascript
基于Node.js的WebSocket通信实现
2017/03/11 Javascript
ES6中Array.copyWithin()函数的用法实例详解
2017/09/16 Javascript
vue中简单弹框dialog的实现方法
2018/02/26 Javascript
详解vue引入子组件方法
2019/02/12 Javascript
[49:42]DOTA2上海特级锦标赛主赛事日 - 3 胜者组第二轮#2Secret VS EG第一局
2016/03/04 DOTA
[01:11:48]Fnatic vs IG 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
对numpy中二进制格式的数据存储与读取方法详解
2018/11/01 Python
python中tkinter的应用:修改字体的实例讲解
2019/07/17 Python
Python3.x+迅雷x 自动下载高分电影的实现方法
2020/01/12 Python
Python如何读取文件中图片格式
2020/01/13 Python
matplotlib 三维图表绘制方法简介
2020/09/20 Python
css3的focus-within选择器的使用
2020/05/11 HTML / CSS
Application Cache未缓存文件无法访问无法加载问题
2014/05/31 HTML / CSS
西安启天科技有限公司网络工程师面试题笔试题
2016/06/12 面试题
期末自我鉴定
2014/01/23 职场文书
学生评语集锦
2015/01/04 职场文书
观看建国大业观后感
2015/06/01 职场文书
PyCharm 配置SSH和SFTP连接远程服务器
2022/05/11 Python