1+ <?php
2+ /**
3+ * php 文件缓存类
4+ */
5+ namespace niklaslu ;
6+
7+ class FileCache{
8+
9+ protected $ filePath ;
10+
11+ public function __construct ($ filePath = '' )
12+ {
13+ $ filePath = $ filePath ? $ filePath : dirname (dirname (__FILE__ )).'/cache/ ' ;
14+
15+ $ this ->filePath = $ filePath ;
16+ }
17+ /**
18+ * 获得缓存数据
19+ * @param $key 缓存名称
20+ * @return mixed
21+ */
22+ public function get ($ key )
23+ {
24+ $ fileName = $ this ->getFileName ($ key );
25+ return $ this ->getFileData ($ fileName );
26+ }
27+ /**
28+ * 设置缓存
29+ * @param $key 缓存名称
30+ * @param $value 缓存值
31+ * @param $expire 有效时间
32+ * @return mixed
33+ */
34+ public function set ($ key , $ value , $ expire = 0 )
35+ {
36+ $ fileName = $ this ->getFileName ($ key );
37+ if (is_file ($ fileName )) {
38+ unlink ($ fileName );
39+ }
40+ $ data = ['data ' => $ value , 'expire ' => $ expire ];
41+ if (file_put_contents ($ fileName , json_encode ($ data ))) {
42+ return true ;
43+ }
44+ return false ;
45+ }
46+ /**
47+ * 是否存在某个缓存
48+ * @param $key 缓存名称
49+ * @return mixed
50+ */
51+ public function isHave ($ key )
52+ {
53+ if (! is_null ($ this ->get ($ key ))) {
54+ return true ;
55+ }
56+ return false ;
57+ }
58+ /**
59+ * 删除缓存
60+ * @param $key 缓存名称
61+ * @return mixed
62+ */
63+ public function delete ($ key )
64+ {
65+ $ fileName = $ this ->getFileName ($ key );
66+ if (is_file ($ fileName )) {
67+ unlink ($ fileName );
68+ return true ;
69+ }
70+ return false ;
71+ }
72+ /**
73+ * 清空所有缓存
74+ * @return mixed
75+ */
76+ public function flush ()
77+ {
78+ $ list = glob ($ this ->filePath . '* ' );
79+ foreach ($ list as $ file ) {
80+ unlink ($ file );
81+ }
82+ return true ;
83+ }
84+ /**
85+ * 获得文件名称
86+ * @param $key
87+ * @return string
88+ */
89+ private function getFileName ($ key )
90+ {
91+ return $ this ->filePath . md5 ($ key );
92+ }
93+ /**
94+ * 获得文件内容
95+ * @param $fileName
96+ */
97+ private function getFileData ($ fileName )
98+ {
99+ if (! is_file ($ fileName )) {
100+ return null ;
101+ }
102+ $ createTime = filectime ($ fileName );
103+ $ data = json_decode (file_get_contents ($ fileName ), true );
104+ //判断是否过期
105+ if ($ data ['expire ' ] != '0 ' && ($ data ['expire ' ] + $ createTime ) < time ()) {
106+ unlink ($ fileName );
107+ return null ;
108+ }
109+ return $ data ['data ' ];
110+ }
111+
112+ }
0 commit comments