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 相关文章推荐
利用 window_onload 实现select默认选择
Oct 09 PHP
php+AJAX传送中文会导致乱码的问题的解决方法
Sep 08 PHP
php加水印的代码(支持半透明透明打水印,支持png透明背景)
Jan 17 PHP
获取PHP警告错误信息的解决方法
Jun 03 PHP
使用php 获取时间今天明天昨天时间戳的详解
Jun 20 PHP
destoon设置自定义搜索的方法
Jun 21 PHP
yii实现创建验证码实例解析
Jul 31 PHP
php实现的Captcha验证码类实例
Sep 22 PHP
PHP获取文件扩展名的4种方法
Nov 24 PHP
php实现当前页面点击下载文件的实例代码
Nov 16 PHP
php 调用百度sms来发送短信的实现示例
Nov 02 PHP
PHP将英文数字转换为阿拉伯数字实例讲解
Jan 28 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
mysql+php分页类(已测)
2008/03/31 PHP
PHP 中执行排序与 MySQL 中排序
2009/04/21 PHP
使用PHPMYADMIN操作mysql数据库添加新用户和数据库的方法
2010/04/02 PHP
日常整理PHP中简单的图形处理(经典)
2015/10/26 PHP
Yii中的cookie的发送和读取
2016/07/27 PHP
实例说明js脚本语言和php脚本语言的区别
2019/04/04 PHP
JS 参数传递的实际应用代码分析
2009/09/13 Javascript
jQuery AJAX 调用WebService实现代码
2010/03/24 Javascript
JQuery实现级联下拉框效果实例讲解
2015/09/17 Javascript
基于javascript bootstrap实现生日日期联动选择
2016/04/07 Javascript
JS中动态创建元素的三种方法总结(推荐)
2016/10/20 Javascript
Vue源码学习之初始化模块init.js解析
2017/11/02 Javascript
vue中动态设置meta标签和title标签的方法
2018/07/11 Javascript
JQuery animate动画应用示例
2019/05/14 jQuery
微信小程序的授权实现过程解析
2019/08/02 Javascript
js函数和this用法实例分析
2020/03/13 Javascript
vue+flask实现视频合成功能(拖拽上传)
2021/03/04 Vue.js
Python  __getattr__与__setattr__使用方法
2008/09/06 Python
通过python下载FTP上的文件夹的实现代码
2013/02/10 Python
分析在Python中何种情况下需要使用断言
2015/04/01 Python
在Python的Bottle框架中使用微信API的示例
2015/04/23 Python
Python实现建立SSH连接的方法
2015/06/03 Python
Python利用turtle库绘制彩虹代码示例
2017/12/20 Python
用python求一个数组的和与平均值的实现方法
2019/06/29 Python
Django框架序列化与反序列化操作详解
2019/11/01 Python
Django choices下拉列表绑定实例
2020/03/13 Python
如何写python的配置文件
2020/06/07 Python
CSS3移动端vw+rem不依赖JS实现响应式布局的方法
2019/01/23 HTML / CSS
英国最大的电子零件及配件零售商:Partmaster
2017/04/24 全球购物
个人实用简单的自我评价
2013/10/19 职场文书
大学生职业生涯规划书的基本内容
2014/01/06 职场文书
老公爱的承诺书
2014/03/31 职场文书
机关作风建设自查报告
2014/10/22 职场文书
大学新生入学感想
2015/08/07 职场文书
利用Python网络爬虫爬取各大音乐评论的代码
2021/04/13 Python
带你了解CSS基础知识,样式
2021/07/21 HTML / CSS