php tpl模板引擎定义与使用示例

本文实例讲述了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基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

(0)

相关推荐

  • 需要使用php模板的朋友必看的很多个顶级PHP模板引擎比较分析

    Smarty Smarty的特点是将模板编译成PHP脚本,然后执行这些脚本.很快,非常灵活. Heyes Template Class 一个非常容易使用,但功能强大并且快速的模板引擎,它帮助你把页面布局和设计从代码中分离. FastTemplate 一个简单的变量插值模板类,它分析你的模板,把变量的值从HTML代码中分离处理. ShellPage 一个简单易用的类,可以让你的整个网站布局基于模板文件,修改模板就能改变整个站点. STP Simple Template Parser 一个简单.轻量

  • 在Yii框架中使用PHP模板引擎Twig的例子

    Twig是一款快速.安全.灵活的PHP模板引擎,它内置了许多filter和tags,并且支持模板继承,能让你用最简洁的代码来描述你的模板.他的语法和Python下的模板引擎Jinjia以及Django的模板语法都非常像. 比如我们在PHP中需要输出变量并且将其进行转义时,语法比较累赘: 复制代码 代码如下: <?php echo $var ?><?php echo htmlspecialchars(\$var, ENT_QUOTES, 'UTF-8') ?> 但是在Twig中可以这

  • php模板引擎技术简单实现

    用了smarty,tp过后,也想了解了解其模板技术是怎么实现,于是写一个简单的模板类,大致就是读取模板文件->替换模板文件的内容->保存或者静态化 tpl.class.php主要解析 assign 方法实现 /** * 模板赋值操作 * @param mixed $tpl_var 如果是字符串,就作为数组索引,如果是数组,就循环赋值 * @param mixed $tpl_value 当$tpl_var为string时的值,默认为 null */ public function assign(

  • PHP模板引擎Smarty的缓存使用总结

    这里我们将分析一下如何开启和使用smarty缓存,如何清除smarty缓存以及smarty的全局缓存,部分缓存,局部缓存三种缓存机制. 一.开启和使用smarty缓存 要开启smarty的缓存,只需在smarty设置参数里面将caching设为true,并指定cache_dir即可.同时设置cache_lefetime参数指定缓存生存时间(单位为秒).如果要对相同页面生成多个不同的缓存,可以在display或fetch中加入第二参数cache_id,如: 复制代码 代码如下: $smarty->

  • ThinkPHP使用smarty模板引擎的方法

    ThinkPHP支持多种php模板引擎,可以根据个人需要加以配置. 下面我们以Smarty模板引擎为例,给大家说说具体的操作流程! 首先去Smarty官网上下载一个Smarty.本站下载地址:http://www.jb51.net/codes/16086.html. 接下来解压压缩包,会有两个文件夹:demo和libs.打开libs文件夹,复制所有内容. 接下来,打开你网站根目录 下thinkphp的文件夹.里面有个vendor文件夹,这个文件夹是TP调用第三方类库用的,把刚才复制的东西全部粘贴

  • 简单的自定义php模板引擎

    模板引擎的思想是来源于MVC(Model View Controller)模型,即模型层.视图层.控制器层. 在Web端,模型层为数据库的操作:视图层就是模板,也就是Web前端:Controller就是PHP对数据和请求的各种操作.模板引擎就是为了将视图层和其他层分离开来,使php代码和html代码不会混杂在一起.因为当php代码和html代码混杂在一起时,将使代码的可读性变差,并且代码后期的维护会变得很困难. 大部分的模板引擎原理都差不多,核心就是利用正则表达式解析模板,将约定好的特定的标识语

  • TMDPHP 模板引擎使用教程

    在PHP界谈模板引擎,必不可免的要拿Smarty开刀, 这个无比傻帽的却又带有一点点官方色彩的模板引擎, 如果没有我这样人富有正义感又富有创新精神的热血青年站出来, 不知道它还要继续毒害多少那些处于花季而又对PHP充满美丽幻想的少年. 1.语法 你真的认为美工学的了 {foreach key=key item=item from=$contact} 这样的语法 却学不了 <?php foreach ($contact as $key=>$item) { ?> 吗? 而 {if $name

  • Pain 全世界最小最简单的PHP模板引擎 (普通版)

    打包下载 Pain.php 复制代码 代码如下: <?php class Pain { public $var=array(); public $tpl=array(); //this is the method to assign vars to the template public function assign($variable,$value=null) { $this->var[$variable]=$value; } public function display($templa

  • PHP中MVC模式的模板引擎开发经验分享

    使Web系统的开发与维护更加方便,从而有效的节省人力物力,受到了越来越多企业的青眯. 模板引擎是MVC模式建立过程的重要方法,开发者可以设计一套赋予含义的标签,通过技术解析处理有效的把数据逻辑处理从界面模板中提取出来,通过解读标签的含义把控制权提交给相应业务逻辑处理程序,从而获取到需要的数据,以模板设计的形式展现出来,使设计人员能把精力更多放在表现形式上.下面是我对模板引擎的认识与设计方法: 说的好听些叫模板引擎,实际就是解读模板数据的过程(个人观点^^).通过我对建站方面的思考认识,网站在展现

  • PHP原生模板引擎 最简单的模板引擎

    复制代码 代码如下: <?php $a = array( 'a','b','c' ); require 'template/demo.php';//引用模板 ?> 模板文件: 复制代码 代码如下: <!DOCTYPE html> <html lang="zh"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-

  • PHP模板引擎Smarty中变量的使用方法示例

    本文实例讲述了PHP模板引擎Smarty中变量的使用方法.分享给大家供大家参考,具体如下: 一.概述: Smarty 是 PHP 众多模板引擎中的一个,它是根据 PHP 编写的一个类库. Smarty 的优点: 1.优化网站访问速度: 2.网页前端设计和程序的分离: 二.Smarty 的安装 1.需要到 Smarty 的官方网站 http://www.smarty.net/download.php 下载最新的 Smarty 版本,比如下载的版本为:Smarty-2.6.18.tar.tar: 2

随机推荐