IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> PHP知识库 -> PHP类 - 模板类 -> 正文阅读

[PHP知识库]PHP类 - 模板类

框架中的模板引擎
模板类

<?php


class Tpl
{
    // 模板文件的路径
    protected $viewDir = './view/';
    // 生成的缓存文件的路径
    protected $cacheDir = './cache/';
    // 过期时间s
    protected $lifeTime = 3600;
    // 用来存放显示变量的数组
    protected $vars = [];

    public function __construct($viewDir = null, $cacheDir = null, $lifeTime = null)
    {
        if(!empty($viewDir)){
            if($this->checkDir($viewDir)){
                $this->viewDir = $viewDir;
            }
        }
        if(!empty($cacheDir)){
            if($this->checkDir($cacheDir)){
                $this->cacheDir = $cacheDir;
            }
        }
        if(!empty($lifeTime)){
            $this->lifeTime = $lifeTime;
        }
    }

    // 判断目录路径是否正确
    protected function checkDir($dirPath)
    {
        // 目录不存在或者不是目录,创建目录
        if(!file_exists($dirPath) || !is_dir($dirPath)){
            return mkdir($dirPath, 0755, true);
        }
        // 判断路径是否可写
        if(!is_writeable($dirPath) || !is_readable($dirPath)){
            return chmod($dirPath, 0755);
        }

        return true;
    }
    // 需要对外公开的方法
    // 分配变量方法
    public function assign($name, $value)
    {
        $this->vars[$name] = $value;
    }
    // 展示缓存文件方法
    // viewName模板文件名
    // isInclude模板文件是仅需编译,还是先编译再包含
    // uri : index.php?page=1 为了让缓存的文件名不重复,将文件名和uri拼接起来再md5,生成缓存的文件名
    public function display($viewName, $isInclude = true, $uri = null)
    {
        // 拼接模板文件的全路径
        $viewPath = rtrim($this->viewDir, '/').'/'.$viewName;
        if(!file_exists($viewPath)){
            die('模板文件不存在');
        }
        // 拼接缓存文件的全路径
        $cacheName = md5($viewName.$uri).'.php';
        $cachePath = rtrim($this->cacheDir,'/').'/'.$cacheName;
        // 根据缓存文件全路径,判断缓存文件是否存在
        if(!file_exists($cachePath)){
            // 缓存不存在 编译模板文件,生成缓存文件
            // 编译模板文件
            $php = $this->compile($viewPath);
            // 写入文件,生成缓存文件
            file_put_contents($cachePath, $php);
        }else{
            // 缓存存在
            // 判断缓存文件是否过期
            $isTimeout = (filectime($cachePath) + $this->lifeTime) > time() ? false:true;
            // 判断模板文件是否被修改过,若模板文件被修改过,缓存文件需要重新生成
            $isChange = filemtime($viewPath) > filemtime($cachePath)?true:false;
            if($isTimeout || $isChange){
                $php = $this->compile($viewPath);
                file_put_contents($cachePath, $php);
            }
            // 判断缓存文件是否需要包含进来
            if($isInclude){
                // 将变量解析出来
                extract($this->vars);
                // 展示缓存文件
                include $cachePath;
            }
        }
    }

    // 编译html文件
    protected function compile($filePath)
    {
        // 读取文件内容
        $html = file_get_contents($filePath);
        // 正则替换[自定义规则]
        $array = [
            '{$%%}' => '<?=$\1; ?>',
            '{foreach %%}' => '<?php foreach (\1): ?>',
            '{/foreach}' => '<?php endforeach?>',
            '{include %%}' => '',
            '{if %%}' => '<?php if (\1): ?>',
        ];
        // 遍历数组,将%%全部替换为 .+ 然后执行正则替换
        // 生成正则表达式
        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正则表达式,$data就是匹配到的内容
    protected function parseInclude($data)
    {
        // 将文件名两边的引号去掉
        $fileName = trim($data[1], '\'"');
        // 不包含文件生成缓存
        $this->display($fileName, false);
        // 拼接缓存文件全路径
        $cacheName = md5($fileName).'.php';
        $cachePath = rtrim($this->cacheDir,'/').'/'.$cacheName;

        return '<?php include "'.$cachePath.'"?>';
    }
}

test.php

<?php
include 'Tpl.php';

$tpl = new TpL();

$title = 'hello';
$data = ['aaa', 'bbb'];
$head = '头部';

$tpl->assign('title', $title);
$tpl->assign('data', $data);
$tpl->assign('head', $head);

$tpl->display('test.html');

./view/test.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{$title}</title>
</head>
<body>
    {include head.html}
    {foreach $data as $value}
    {$value}<br/>
    {/foreach}
</body>
</html>

./view/head.html

<div>{$head}</div>
  PHP知识库 最新文章
Laravel 下实现 Google 2fa 验证
UUCTF WP
DASCTF10月 web
XAMPP任意命令执行提升权限漏洞(CVE-2020-
[GYCTF2020]Easyphp
iwebsec靶场 代码执行关卡通关笔记
多个线程同步执行,多个线程依次执行,多个
php 没事记录下常用方法 (TP5.1)
php之jwt
2021-09-18
上一篇文章      下一篇文章      查看所有文章
加:2021-08-06 09:23:16  更:2021-08-06 09:25:39 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/28 4:34:45-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码