cache.php 代码如下:
PHP代码
01.
02./*
03.用户需要事先定义的常量:
04._CachePath_ 模板缓存路径
05._CacheEnable_ 自动缓存机制是否开启,未定义或为空,表示关闭自动缓存机制
06._ReCacheTime_ 自动重新缓存间隔时间,单位为秒,未定义或为空,表示关闭自动重新缓存
07.*/
08.
09.class cache {
10.
11.var $cachefile;
12.var $cachefilevar;
13.
14.function cache() {
15. //生成当前页的Cache组文件名 $this->cachefilevar 及文件名 $this->cachefile
16. //动态页的参数不同对应的Cache文件也不同,但是每一个动态页的所有Cache文件都有相同的文件名,只是扩展名不同
17. $s=array(".","/");$r=array("_","");
18. $this->cachefilevar=str_replace($s,$r,$_SERVER["SCRIPT_NAME"])."_".$_GET[_ActionVar_];
19. $this->cachefile=$this->cachefilevar.".".md5($_SERVER["REQUEST_URI"]);
20.}
21.
22.//删除当前页/模块的缓存
23.function delete() {
24. //删除当前页的缓存
25. $d = dir(_CachePath_);
26. $strlen=strlen($this->cachefilevar);
27. //返回当前页的所有Cache文件组
28. while (false !== ($entry = $d->read())) {
29. if (substr($entry,0,$strlen)==$this->cachefilevar) {
30. if (!unlink(_CachePath_."/".$entry)) {echo "Cache目录无法写入";exit;}
31. }
32. }
33.}
34.
35.//判断是否已Cache过,以及是否需要Cache
36.function check() {
37. //如果设置了缓存更新间隔时间 _ReCacheTime_
38. if (_ReCacheTime_+0>0) {
39. //返回当前页Cache的最后更新时间
40. $var=@file(_CachePath_."/".$this->cachefilevar);$var=$var[0];
41. //如果更新时间超出更新间隔时间则删除Cache文件
42. if (time()-$var>_ReCacheTime_) {
43. $this->delete();$ischage=true;
44. }
45. }
46. //返回当前页的Cache
47. $file=_CachePath_."/".$this->cachefile;
48. //判断当前页Cache是否存在 且 Cache功能是否开启
49. return (file_exists($file) and _CacheEnable_ and !$ischange);
50.}
51.
52.//读取Cache
53.function read() {
54. //返回当前页的Cache
55. $file=_CachePath_."/".$this->cachefile;
56. //读取Cache文件的内容
57. if (_CacheEnable_) return readfile($file);
58. else return false;
59.}
60.
61.//生成Cache
62.function write($output) {
63. //返回当前页的Cache
64. $file=_CachePath_."/".$this->cachefile;
65. //如果Cache功能开启
66. if (_CacheEnable_) {
67. //把输出的内容写入Cache文件
68. $fp=@fopen($file,'w');
69. if (!@fputs($fp,$output)) {echo "模板Cache写入失败";exit;}
70. @fclose($fp);
71. //如果设置了缓存更新间隔时间 _ReCacheTime_
72. if (_ReCacheTime_+0>0) {
73. //更新当前页Cache的最后更新时间
74. $file=_CachePath_."/".$this->cachefilevar;
75. $fp=@fopen($file,'w');
76. if (!@fwrite($fp,time())) {echo "Cache目录无法写入";exit;}
77. @fclose($fp);
78. }
79. }
80.}
81.
82.}
83.?>
使用过程:
PHP代码
01.<?php
02. define("_CachePath_","./cache/");
03. define("_CacheEnable_","1");
04. define("_ReCacheTime_","43200");
05. include('cache.php');
06. $cache=new cache();
07. if ($cache->check()) {
08. $template=$cache->read();
09. }else {
10. ob_start();
11. ob_implicit_flush(0);
12. ?>
13. 页面内容。。。。
14.<?php
15. $template = ob_get_contents();
16. $cache->write($template);
17. }
18. ?>
缓存在实际使用当中应用很广泛,可以减轻对服务器数据库的访问,提高运行速度。目前很多CMS内容管理系统中频繁使用缓存机制来提高系统运行的效率。