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 相关文章推荐
别人整理的服务器变量:$_SERVER
Oct 20 PHP
Eclipse中php插件安装及Xdebug配置的使用详解
Apr 25 PHP
php小经验:解析preg_match与preg_match_all 函数
Jun 29 PHP
php函数间的参数传递(值传递/引用传递)
Sep 23 PHP
yii实现级联下拉菜单的方法
Jul 31 PHP
PHP生成条形码大揭秘
Sep 24 PHP
thinkPHP中多维数组的遍历方法
Jan 09 PHP
PHP使用php-resque库配合Redis实现MQ消息队列的教程
Jun 29 PHP
PHP实现合并两个排序链表的方法
Jan 19 PHP
Laravel 使用查询构造器配合原生sql语句查询的例子
Oct 12 PHP
php利用ZipArchive类操作文件的实例
Jan 21 PHP
PHP safe_mode开启对于PHP系统函数有什么影响
Nov 10 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 DOMElement 操作xml 文档的实现代码
2013/05/10 PHP
PHP中使用匿名函数操作数据库的例子
2014/11/17 PHP
Jquery中val()表单取值赋值的实例代码
2013/08/15 Javascript
javascript面向对象之访问对象属性的两种方式分析
2015/01/13 Javascript
AngularJS中如何使用$http对MongoLab数据表进行增删改查
2016/01/23 Javascript
浅谈JS原型对象和原型链
2016/03/02 Javascript
javascript实现不同颜色Tab标签切换效果
2016/04/27 Javascript
BootStrap 导航条实例代码
2017/05/18 Javascript
Bootstrap Table快速完美搭建后台管理系统
2017/09/20 Javascript
Node.js对MongoDB进行增删改查操作的实例代码
2019/04/18 Javascript
Vue props中Object和Array设置默认值操作
2020/07/30 Javascript
Python函数学习笔记
2008/10/07 Python
在Python中使用PIL模块处理图像的教程
2015/04/29 Python
利用Python获取赶集网招聘信息前篇
2016/04/18 Python
使用Python的Twisted框架编写非阻塞程序的代码示例
2016/05/25 Python
对numpy 数组和矩阵的乘法的进一步理解
2018/04/04 Python
Python3实现的字典、列表和json对象互转功能示例
2018/05/22 Python
Numpy数组array和矩阵matrix转换方法
2019/08/05 Python
Python argparse模块应用实例解析
2019/11/15 Python
Python正则表达式急速入门(小结)
2019/12/16 Python
django xadmin action兼容自定义model权限教程
2020/03/30 Python
python 比较字典value的最大值的几种方法
2020/04/17 Python
Python计算信息熵实例
2020/06/18 Python
python实现邮件循环自动发件功能
2020/09/11 Python
英国图书音像网站:Hive.co.uk(图书、电子书、DVD、蓝光、音乐CD等)
2017/10/16 全球购物
在网上学习全世界最好的课程:Coursera
2017/11/07 全球购物
英国厨房与餐具用品为主的设计品牌:Joseph Joseph
2018/04/26 全球购物
给水工程专业毕业生自荐信
2014/01/28 职场文书
计算机学生求职信范文
2014/01/30 职场文书
工厂总经理岗位职责
2014/02/07 职场文书
《雷雨》教学反思
2014/02/20 职场文书
党校个人自我鉴定范文
2014/03/28 职场文书
单位在职证明书
2014/09/11 职场文书
二手房购房意向书
2015/05/09 职场文书
运动会广播稿300字
2015/08/19 职场文书
java实现web实时消息推送的七种方案
2022/07/23 Java/Android