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 相关文章推荐
某大型网络公司应聘时的笔试题目附答案
Mar 27 PHP
php格式化工具Beautify PHP小小BUG
Apr 24 PHP
PHP SEO优化之URL优化方法
Apr 21 PHP
thinkphp视图模型查询提示ERR: 1146:Table 'db.pr_order_view' doesn't exist的解决方法
Oct 30 PHP
使用php的HTTP请求的库Requests实现美女图片墙
Feb 22 PHP
php中使用gd库实现远程图片下载实例
May 12 PHP
PHP下载远程图片并保存到本地方法总结
Jan 22 PHP
简单谈谈php浮点数精确运算
Mar 10 PHP
删除PHP数组中头部、尾部、任意元素的实现代码
Apr 10 PHP
php基于自定义函数记录log日志方法
Jul 21 PHP
kindeditor 加入七牛云上传的实例讲解
Nov 12 PHP
php和html的区别点详细总结
Sep 24 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
JAVA/JSP学习系列之四
2006/10/09 PHP
PHP实现生成带背景的图形验证码功能
2016/10/03 PHP
学习ExtJS accordion布局
2009/10/08 Javascript
jquery实现可拖动DIV自定义保存到数据的实例
2013/11/20 Javascript
javascript中call和apply的用法示例分析
2015/04/02 Javascript
简单的jQuery入门指引
2015/07/28 Javascript
基于JS实现PHP的sprintf函数实例
2015/11/14 Javascript
JavaScript toUpperCase()方法使用详解
2016/08/26 Javascript
JavaScript实现Java中Map容器的方法
2016/10/09 Javascript
vue.js动态数据绑定学习笔记
2017/05/19 Javascript
jquery实现动态创建form并提交的方法示例
2019/05/27 jQuery
vue h5移动端禁止缩放代码
2019/10/28 Javascript
vue实现简单加法计算器
2020/10/22 Javascript
Vue+Bootstrap实现简易学生管理系统
2021/02/09 Vue.js
[01:05]DOTA2完美大师赛趣味视频之选手教你打职业
2017/11/23 DOTA
Python实现删除Android工程中的冗余字符串
2015/01/19 Python
Django框架中方法的访问和查找
2015/07/15 Python
实例讲解Python设计模式编程之工厂方法模式的使用
2016/03/02 Python
Python中.py文件打包成exe可执行文件详解
2017/03/22 Python
解决Python selenium get页面很慢时的问题
2019/01/30 Python
PyTorch学习:动态图和静态图的例子
2020/01/06 Python
python中68个内置函数的总结与介绍
2020/02/24 Python
python GUI库图形界面开发之PyQt5单行文本框控件QLineEdit详细使用方法与实例
2020/02/27 Python
在Mac中PyCharm配置python Anaconda环境过程图解
2020/03/11 Python
pytorch 常用函数 max ,eq说明
2020/06/28 Python
10分钟入门CSS3 Animation
2018/12/25 HTML / CSS
HTML5 Canvas draw方法制作动画效果示例
2013/07/11 HTML / CSS
Pam & Gela官网:美国性感前卫女装品牌
2018/07/19 全球购物
OLEDBConnection和SQLConnection有什么区别
2013/05/31 面试题
群众路线领导干部个人对照检查材料(集锦)
2014/09/23 职场文书
以权谋私检举信范文
2015/03/02 职场文书
2015年教研组工作总结
2015/05/04 职场文书
女方家长婚礼致辞
2015/07/27 职场文书
python实现简单区块链结构
2021/04/25 Python
MySQL数据库10秒内插入百万条数据的实现
2021/11/01 MySQL
MySQL的InnoDB存储引擎的数据页结构详解
2022/03/03 MySQL