Home > php教程 > php手册 > body text

简单的页面缓冲技术(二)

WBOY
Release: 2016-06-21 09:10:12
Original
985 people have browsed it

页面

我的具体实现的例子
  为了帮助大家有个感性认识,这里我给出在我的主页上实现的基于文件处理的方法。只有主要的处理代码,不完整。

1 $tmpfile="../tmp/".basename($REQUEST_URI);
2 $tmpfile=str_replace("?", "_", $tmpfile);
3 $tmpfile=str_replace("&", "_", $tmpfile);
4 if(file_exists($tmpfile))
5 {
6 $cflag=false;
7 $dtmp=filemtime($tmpfile);
8 $itmp=filemtime($incfile);
9 $cflag=$cflag | ($dtmp 10 $ctmp=filemtime(basename($PHP_SELF));
11 $cflag=$cflag | ($dtmp 12 $ttmp=filemtime("template/content.ihtml");
13 $cflag=$cflag | ($dtmp 14 }
15 else
16 $cflag=true;
17
18 if(!$cflag) //使用存在的文件
19 {
20 readfile($tmpfile);
21 exit;
22 }
23
24 //创建新的文件
25 include "template.class.php3";
26
27 $fp=fopen($incfile, "r");
28 $content=fread($fp, filesize($incfile));
29 fclose($fp);
30
31 //下面进行模版处理
32 $t = new Template("template", "keep");
33
34 $t->set_file("contentfile","content.ihtml");
35
36 $t->set_var(
37 array(
38 "content"=>$content
39 ));
40
41 $t->parse("outputcontent","contentfile");
42
43 $fp=fopen($tmpfile, "w");
44 if($fp)
45 {
46 flock($fp, 3);
47 fwrite($fp, $t->get_var("outputcontent"));
48 flock($fp, 1);
49 fclose($fp);
50 }
51 $t->p("outputcontent");
?>


  先向大家介绍一下我的目录结构:

  /---bin/ 执行程序目录
  | |--content.php3 用于处理文件显示的程序
  | |--template/ 用于存放模板文件的目录
  | |---content.ihtml 模板文件
  |-docs/ 数据文件
  |-tmp/ 存放缓冲文件

  content.php3文件用来处理动态页面。用户可以通过content.php3?page=id号来读出一个数据文件。具体方法我就不说了,大家只要知道每个数据文件都有一个不同的id号,这样content.php3?page=id号的方式就可以唯一标识一个数据文件。

第1-3行,生成临时文件名。将'?','&'等字符替换成'_'。
第4行,判断临时文件名是否存在,如果有则执行第18-22行,并结束。
第6-13行,判断与生成动态页面有关的文件修改时间与临时文件哪个更新,设置重新生成标志。在这里使用  filemtime()来得到最后修改时间。
第24-41行,利用模板类生成动态结果,放在变量中。关于模板的处理可以参考《模板,PHPLIB处理方式》一文。
第43-50行,生成临时文件。此处对文件进行了加锁处理,以象写冲突。
第51行,输出结果。

  这就是我的处理,大家可以自行修改。

  缓冲是一项有意义的技术,可以提高访问速度,减少系统消耗。不过方法可能有多种多样,大家可以自由发挥。

本站注:看了这篇文章,竟发现本文作者的思路和本站的静态文章更新的实现原理是一样的。不同的是,本站的文章是每四天定期更新的。如果有兴趣的朋友可以通过页面下方的"view source"链接来查看具体实现的代码。如果有什么疑问和好的思想,欢迎到论坛共同讨论。



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!