-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMiniCache.php
359 lines (312 loc) · 9.3 KB
/
MiniCache.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<?php
/**
* ------------------------------------------------------
* MiniCache
*
* A small, lightweight cache system for PHP5 or newer
*
* @author Brian Haveri
* @link http://github.com/brianhaveri/MiniCache
* @license MIT License http://en.wikipedia.org/wiki/MIT_License
* ------------------------------------------------------
*/
include(dirname(__FILE__).'/MiniCacheConfig.php');
class MiniCache {
/*
* ------------------------------------------------------
* Array keys used throughout class
* You probably won't change these (but still optional)
* ------------------------------------------------------
*/
const CACHEAGE = 'age';
const CACHEDATA = 'data';
const CACHEDURATION = 'duration';
const CACHEID = 'id';
const CACHEINFO = 'info';
const CACHEKEY = 'key';
/*
* ------------------------------------------------------
* Do not change these
* ------------------------------------------------------
*/
private static $_instance; // Singleton instance
private $_loaded = array(); // Intermediate storage of loaded cache items
/**
* ------------------------------------------------------
* Returns a singleton
* This is the instantiation method
* @return object
* ------------------------------------------------------
*/
static function getInstance() {
if( ! isset(self::$_instance)) {
$c = __CLASS__;
self::$_instance = new $c;
}
return self::$_instance;
}
/**
* ------------------------------------------------------
* Destroy the instance
* ------------------------------------------------------
*/
public function destroyInstance() {
self::$_instance->_loaded = array();
self::$_instance = NULL;
}
/**
* ------------------------------------------------------
* Nothing actually happens in the constructor, but we
* need to declare it with private visibility to
* force instantiation through getInstance().
*
* If you try to instantiate through the constructor,
* you will receive a PHP error.
* ------------------------------------------------------
*/
private function __construct() {}
/**
* ------------------------------------------------------
* Returns data for a cache item.
* Return datatype will match datatype saved using set()
* Returns FALSE if an error occurred
* @param string $id
* @return mixed|bool
* ------------------------------------------------------
*/
public function get($id) {
$cacheKey = self::cacheKey($id);
$data = $this->_get($cacheKey);
if(is_array($data) && array_key_exists(self::CACHEDATA, $data)) {
return $data[self::CACHEDATA];
}
return FALSE;
}
/**
* ------------------------------------------------------
* Returns metadata for a cache item
* Returns FALSE if an error occurred
* @param string $id
* @return array|bool
* ------------------------------------------------------
*/
public function getInfo($id) {
$cacheKey = self::cacheKey($id);
$data = $this->_get($cacheKey);
if(is_array($data) && array_key_exists(self::CACHEINFO, $data)) {
// Age isn't directly stored in the cache file, so calculate it
$data[self::CACHEINFO][self::CACHEAGE] = $this->_getAge($cacheKey);
return $data[self::CACHEINFO];
}
return FALSE;
}
/**
* ------------------------------------------------------
* Saves a cache item to disk
* The data provided may be of any datatype including
* object, array, string, etc.
*
* The saved data and corresponding metadata is
* saved to disk as a serialized PHP multidimensional array.
*
* @param string $id
* @param mixed $data
* @param integer $duration
* @return bool
* ------------------------------------------------------
*/
public function set($id, $data, $duration = NULL) {
if(! is_int($duration)) { $info[self::CACHEDURATION] = MINICACHE_DURATION; }
$cacheKey = self::cacheKey($id);
$fpath = $this->_fpath($cacheKey);
$cacheData = array(
self::CACHEDATA => $data,
self::CACHEINFO => array(
self::CACHEDURATION => $duration,
self::CACHEID => $id,
self::CACHEKEY => $cacheKey
)
);
$serializedData = serialize($cacheData);
if(file_put_contents($fpath, $serializedData, LOCK_EX)) {
chmod($fpath, 0777);
self::getInstance()->_loaded[$cacheKey] = $cacheData;
return TRUE;
}
return FALSE;
}
/**
* ------------------------------------------------------
* Deletes a cache item
* @param string $id
* @return bool
* ------------------------------------------------------
*/
public function delete($id) {
$cacheKey = self::cacheKey($id);
// Delete from instance vars
if(is_array(self::getInstance()->_loaded) && array_key_exists($cacheKey, self::getInstance()->_loaded)) {
unset(self::getInstance()->_loaded[$cacheKey]);
}
// Delete from disk
$fpath = $this->_fpath($cacheKey);
if(file_exists($fpath)) {
return unlink($fpath);
}
return FALSE;
}
/**
* ------------------------------------------------------
* Deletes all cache items
* Returns number of items deleted
* @return integer
* ------------------------------------------------------
*/
public function deleteAll() {
$numDeleted = 0;
$items = $this->listAll();
if(is_array($items)) {
foreach($items as $cacheKey=>$item) {
$info =& $item[self::CACHEINFO];
$numDeleted += (int) $this->delete($info[self::CACHEID]);
}
}
return $numDeleted;
}
/**
* ------------------------------------------------------
* Deletes only expired cache items
* Returns number of items deleted
* @return integer
* ------------------------------------------------------
*/
public function deleteExpired() {
$numDeleted = 0;
$items = $this->listAll();
if(is_array($items)) {
foreach($items as $cacheKey=>$item) {
$info =& $item[self::CACHEINFO];
if(is_array($info)) {
if(self::isExpired($this->_getAge($info[self::CACHEKEY]), $info[self::CACHEDURATION])) {
$numDeleted += (int) $this->delete($info[self::CACHEID]);
}
}
}
}
return $numDeleted;
}
/**
* ------------------------------------------------------
* Returns keys and info for all items
* @return array
* ------------------------------------------------------
*/
public function listAll($startDir=NULL) {
if(is_null($startDir)) { $startDir = MINICACHE_PATH; }
$files = scandir($startDir);
$items = array();
if($files && count($files) > 0) {
foreach($files as $k=>$fname) {
if(in_array($fname, array('.', '..', '.svn'))) { continue; }
if(is_dir($startDir.'/'.$fname)) {
$items = array_merge($items, $this->listAll($startDir.'/'.$fname));
continue;
}
$data = $this->_get(basename($fname, MINICACHE_FEXT));
$cacheKey = $data[self::CACHEINFO][self::CACHEKEY];
unset(self::getInstance()->_loaded[$cacheKey]);
unset($data[self::CACHEDATA]);
$items[$cacheKey] = $data;
}
ksort($items);
return $items;
}
return array();
}
/**
* ------------------------------------------------------
* Returns all data (regular and metadata) for a cache item
* Returns FALSE if an error occurred
* @param string $cacheKey
* @return array
* ------------------------------------------------------
*/
private function _get($cacheKey) {
// _get() is called by multiple methods
// so we intermediately store and read the data using _loaded
// to minimize disk reads
// Use data in _loaded if possible
if(is_array(self::getInstance()->_loaded) && array_key_exists($cacheKey, self::getInstance()->_loaded)) {
return self::getInstance()->_loaded[$cacheKey];
}
// Data wasn't in _loaded, so let's read from disk
$fpath = $this->_fpath($cacheKey);
if(file_exists($fpath)) {
$data = unserialize(file_get_contents($fpath));
if(is_array($data)) {
self::getInstance()->_loaded[$cacheKey] = $data;
return $data;
}
}
return FALSE;
}
/**
* ------------------------------------------------------
* Returns a full path for a cache item
* @param string $cacheKey
* @return string
* ------------------------------------------------------
*/
private function _fpath($cacheKey) {
$path = MINICACHE_PATH;
if(MINICACHE_DEPTH > 0) {
$segments = array_slice(str_split($cacheKey), 0, MINICACHE_DEPTH);
$path .= join('/', $segments);
if(! file_exists($path)) {
mkdir($path, 0777, TRUE);
}
}
return join('', array(
$path.'/',
$cacheKey,
MINICACHE_FEXT
));
}
/**
* ------------------------------------------------------
* Has the cache file expired?
* @param integer $age
* @param integer $duration
* @return bool
* ------------------------------------------------------
*/
public static function isExpired($age, $duration) {
return ($duration >= 0 && $age > $duration);
}
/**
* ------------------------------------------------------
* Generate a cache key
* @param string $id
* @return string
* ------------------------------------------------------
*/
public static function cacheKey($id) {
return md5($id);
}
/**
* ------------------------------------------------------
* Returns age of cache file (seconds)
* Returns FALSE if an error occurred
* @param string $cacheKey
* @return integer|bool
* ------------------------------------------------------
*/
private function _getAge($cacheKey) {
$fpath = $this->_fpath($cacheKey);
if(file_exists($fpath)) {
return time() - filemtime($fpath);
}
return FALSE;
}
}
?>