php操作IO的速度很快,估计是直接调用C的函数,拿来做缓存是不错的,CMS有大量类似的应用。
include目录config.php:
1 define('ROOT_PATH', str_replace('include/config.php', '', str_replace('\\', '/', __FILE__)));
library目录 cls_filecache.php:
1 <?php
2 define('ROOT_PATH', str_replace('library/index.php', '', str_replace('\\', '/', __FILE__)));
3 require_once ROOT_PATH.'include/config.php';
4 class FileCache{
5 var $path='';
6 static $cache;
7 public function __construct($folder='caches') {
8 $this->path=ROOT_PATH.$folder;
9 if(!is_dir(ROOT_PATH.$folder)){
10 mkdir(ROOT_PATH.$folder);
11 }
12 }
13 //添加/修改缓存
14 function add($key,$val){
15 //echo FileCache::$cache;
16 //FileCache::$cache['test']='asdqew';
17 $cachefile=$this->path.'/'.$key.'.php';
18 $content = '<?php ';
19 $content .= '$data = ' . var_export($val, true) .'; ';
20 $content .= '?>';
21 file_put_contents($cachefile, $content, LOCK_EX);
22 }
23 //获取缓存
24 function get($key){
25 //echo FileCache::$cache[$key];
26 if(!is_null(FileCache::$cache[$key])){
27 return FileCache::$cache[$key];
28 }
29 $cache_file_path = $this->path.'/'.$key.'.php';
30 if (file_exists($cache_file_path))
31 {
32 include_once($cache_file_path);
33 //echo $data;
34 FileCache::$cache[$key] = $data;
35 //echo FileCache::$cache[$key];
36 return FileCache::$cache[$key];
37 }
38 else
39 {
40 return false;
41 }
42 }
43 //删除缓存
44 function delete($key){
45 //echo FileCache::$cache[$key]=null;
46 if(is_dir($this->path)){
47 if(file_exists($this->path.'/'.$key.'.php')){
48 if(unlink($this->path.'/'.$key.'.php')){
49 FileCache::$cache[$key]=null;
50 return true;
51 }else{
52 return false;
53 }
54 }else{
55 return true;
56 }
57 }else{
58 return true;
59 }
60 }
61 //删除所有缓存
62 function deleteAll(){
63 if(is_dir($this->path)){
64 $dir=opendir($this->path);
65 while(false!==($file=readdir($dir))){
66 $files[]=$file;
67 }
68 closedir($dir);
69 if($files){//文件夹不为空,包括 . 和 ..2个特殊文件夹
70 $isdel=true;
71 foreach($files as $f){
72 if($f!='.' && $f!='..')
73 $isdel=&unlink($this->path.'/'.$f);
74 }
75 if($isdel){
76 FileCache::$cache=null;
77 }
78 return $isdel;
79 }else
80 return false;
81 }
82 }
83 }
84 ?>
调用测试文件:
1 <?php
2 require_once 'include/config.php';
3 require_once 'library/cls_filecache.php';
4 $cache=new FileCache();
5 $cache->add('test', 123);
6 $cache->add('test', 'asd');
7 echo $cache->get('test');
8 echo $cache->get('test2');
9 $cache->delete('test');
10 echo $cache->get('test');
11 echo $cache->get('test2');
12 $cache->deleteAll();
13 echo $cache->get('test');
14 echo $cache->get('test2');
15 ?>
转自:http://babyhey.com/forum.php?mod=viewthread&tid=165&extra=page%3D1