1 class File
2 {
3 private $_dir;
4 const EXT = '.txt';
5
6 public function __construct()
7 {
8 $this->_dir = dirname(__FILE__).'/files';
9 }
10
11 public function cacheData($key, $value='', $path = ''){
12
13 # 拼接文件名
14 $filename = $this->_dir.$path.'/'.$key.self::EXT;
15
16 # 写入缓存
17 if ($value !== '') {
18
19 # 删除缓存
20 if (is_null($value)) {
21 return unlink($filename);
22 }
23
24 $dir = dirname($filename);
25
26 # 判断目录是否存在
27 if (!is_dir($dir)) {
28 mkdir($dir,0777);
29 }
30
31 return file_put_contents($filename, json_encode($value));
32
33 # 读取缓存
34 }else{
35
36 if (!is_file($filename)) {
37 return false;
38 }else{
39
40 # 解析json字符串并返回
41 return json_decode(file_get_contents($filename),true);
42 }
43 }
44 }
45 }
1 $file = new File;
2
3 $data['id'] = 1;
4 $data['name'] = 'yach';
5 $data['data'][] = 1;
6 $data['data'][] = 3;
7 $data['data']['msg'] = 'helloword';
8
9 # 添加
10 $file->cacheData('test',$data);
11
12 # 读取
13 $file->cacheData('test');
14
15 # 删除
16 $file->cacheData('test',null);