今天自己研究了一下静态页面,其实也没有那么高深。当然,我现在实现的只是最简单的情况,只能根据过期时间来处理,后面还有由数据的更新来触发静态页面的更新,等等更加有效地手段,还有很长的路要走。如果我继续研究下去,并且有所收获的话,也会在这篇博客里持续更新。
这是基于phpcms的,一个模块实现一类功能,由一系列控制器组成,模板就不用说了吧,用过mvc框架的朋友都知道,生成的静态页面按模块存放。
首先检查静态页面是否过期,未过期则直接输出,否则重新解析模板并运行,生成新的静态页面,同时返回给浏览器。其中template()函数是平衡phpcms中解析模板的一个函数。
忽略其中的$style和$filepath吧
<?php
/**
* 生成静态页面并缓存
* @param String $module 模块名
* @param String $template 模板名
* @param int $expire 到期时间
* @param String $style
*/
function html_cache($module = 'content', $template = 'index', $expire, $style = '')
{
$style = SITE_NAME ? SITE_NAME: 'default';
$filepath = '静态页面的路径,与模块名还有上面的$style有关';
$filename = $filepath . DIRECTORY_SEPARATOR . $template . '.html';
if ((time() > $expire) || !file_exists($filename))
{
ob_start();
include template($module, $template, $style);
$out = ob_get_contents();
ob_end_flush();
if (!is_dir($filepath))
{
mkdir($filepath, 0777, true);
}
file_put_contents($filename, $out);
chmod($filename, 0777);
}
else
{
echo file_get_contents($filename);
}
return;
}
?>
那么,如何更好地选择页面更新的时机呢?欢迎大家提意见,一起交流,共同进步。