动态语言静态化

什么是动态语言静态化?

将现有PHP等动态语言的逻辑代码生成为静态HTML文件,用户访问动态脚本重定向到静态HTML文件的过程。
对实时性要求不高的页面。

为什么要静态化?

  • 动态脚本通常会做逻辑计算和数据查询,访问量越大,服务器压力越大
  • 访问量大时可能会造成CPU负载过高,数据库服务器压力过大
  • 静态化可以降低逻辑处理压力,降低数据库服务器查询压力

静态化的实现方式

一、使用模板引擎 - Smarty

利用Smarty的缓存机制生成静态HTML缓存文件

//config
$smarty->cache_dir = $ROOT.'/cache';//缓存目录
$smarty->caching = true;//是否开启缓存
$smarty->cache_lifetime = "3600";//缓存时间
//display
$smarty->display(template[, cache_id[, compile_id]]):
//clear
$smarty->clear_all_cache();//清除所有缓存
$smarty->clear_cache('file.html');//清除指定的缓存
$smarty->clear_cache('article.html', $arti_id);//清除同一个模板下的指定缓存ID的缓存

二、使用ob系列函数

//相关函数
ob_start()://打开输出控制缓冲
ob_get_contents()://返回输出缓冲区内容
ob_clean()://清空输出缓冲区
ob_end_flush()://冲刷出缓冲区内容并关闭缓冲

判断是否过期使用文件的inode修改时间,可用PHP里的 filectime() 函数。
示例如下:

 <?php
$id = $_GET['id'];
$cache_name = md5(__FILE__).'-'.$id.'.html';
$cache_lifetime = 3600;
if(filectime(__FILE__) <= filectime($cache_name) && file_exists($cache_name) && filectime($cache_name) + 3600 > time()){
  include $cache_name;
  exit;
}
ob_start();
 ?>
 <b>This is My Great Wall id = <?php echo $id ?></b>
 <?php
$content = ob_get_contents();
ob_end_flush();
$handle = fopen($cache_name, 'w');
fwrite($handle, $content);
fclose($handle);
?>
posted @ 2021-01-29 16:37  皎然CEO  阅读(78)  评论(0编辑  收藏  举报