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源代码
Aug 21 PHP
使用php记录用户通过搜索引擎进网站的关键词
Feb 13 PHP
php使用imagick模块实现图片缩放、裁剪、压缩示例
Apr 17 PHP
ThinkPHP模板之变量输出、自定义函数与判断语句用法
Nov 01 PHP
php递归遍历删除文件的方法
Apr 17 PHP
php生成图片验证码的实例讲解
Aug 03 PHP
[原创]PHP简单开启curl的方法(测试可行)
Jan 11 PHP
验证坐标在某坐标区域内php代码
Oct 08 PHP
php版微信js-sdk支付接口类用法示例
Oct 12 PHP
PHP使用mongoclient简单操作mongodb数据库示例
Feb 08 PHP
在Laravel中实现使用AJAX动态刷新部分页面
Oct 15 PHP
关于Yii2框架跑脚本时内存泄漏问题的分析与解决
Dec 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输出echo、print、print_r、printf、sprintf、var_dump的区别比较
2013/06/21 PHP
php bootstrap实现简单登录
2016/03/08 PHP
一个实用的php验证码类
2017/07/06 PHP
ie和firefox不兼容的解决方法集合
2009/04/28 Javascript
js写出遮罩层登陆框和对联广告并自动跟随滚动条滚动
2014/04/29 Javascript
网页下载文件期间如何防止用户对网页进行其他操作
2014/06/27 Javascript
JavaScript设计模式之单件模式介绍
2014/12/28 Javascript
Javascript定义类(class)的三种方法详解
2015/03/13 Javascript
JS创建事件的三种方法(实例代码)
2016/05/12 Javascript
详解JavaScript实现设计模式中的适配器模式的方法
2016/05/18 Javascript
详解Webpack+Babel+React开发环境的搭建的方法步骤
2018/01/09 Javascript
vue中引用阿里字体图标的方法
2018/02/10 Javascript
微信小程序实现手指触摸画板
2018/07/09 Javascript
Vue中使用clipboard实现复制功能
2018/09/05 Javascript
Vue cli3 库模式搭建组件库并发布到 npm的流程
2018/10/12 Javascript
Vue中的nextTick作用和几个简单的使用场景
2021/01/25 Vue.js
Python数据类型详解(二)列表
2016/05/08 Python
Python中矩阵库Numpy基本操作详解
2017/11/21 Python
python实现公司年会抽奖程序
2019/01/22 Python
教你如何编写、保存与运行Python程序的方法
2019/07/12 Python
django rest framework 过滤时间操作
2020/07/12 Python
python 视频下载神器(you-get)的具体使用
2021/01/06 Python
详解Python+Selenium+ChromeDriver的配置和问题解决
2021/01/19 Python
数控技术与应用毕业生自荐信
2013/09/24 职场文书
应届生自我鉴定
2013/12/11 职场文书
领导检查欢迎词
2014/01/14 职场文书
更夫岗位责任制
2014/02/11 职场文书
新闻专业学生的自我评价
2014/02/13 职场文书
2014两会优秀的心得体会范文
2014/03/17 职场文书
医疗专业毕业生求职信
2014/08/28 职场文书
考试保密承诺书
2014/08/30 职场文书
大三学年自我鉴定范文(3篇)
2014/09/28 职场文书
助学金感谢信
2015/01/20 职场文书
北京故宫导游词
2015/01/31 职场文书
环境卫生标语
2015/08/03 职场文书
思想品德课教学反思
2016/02/24 职场文书