forked from andygott/PHP-Cache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphpcache.php
More file actions
127 lines (86 loc) · 2.29 KB
/
phpcache.php
File metadata and controls
127 lines (86 loc) · 2.29 KB
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
<?php
namespace reallysimple;
interface PhpCacheInterface {
public function store($key, $data, $ttl = 0);
public function fetch($key);
public function delete($key);
}
class PhpCache implements PhpCacheInterface {
private $_cache;
public function __construct($cache_dir = false) {
if (extension_loaded('apc')) {
$this->_cache = new PhpApcCache();
}
else if ($cache_dir) {
$this->_cache = new PhpFileCache($cache_dir);
}
else {
throw new \Exception('APC is not installed, and no cache directory was specified for file cache.');
}
}
public function store($key, $data, $ttl = 0) {
return $this->_cache->store($this->_getKey($key), $data, $ttl);
}
public function fetch($key, $expires = false) {
return $this->_cache->fetch($this->_getKey($key), $expires);
}
public function delete($key) {
return $this->_cache->delete($this->_getKey($key));
}
private function _getKey($key) {
return md5($key);
}
}
class PhpApcCache implements PhpCacheInterface {
public function store($key, $data, $ttl = 0) {
return apc_store($key, $data, $ttl);
}
public function fetch($key) {
return apc_fetch($key);
}
public function delete($key) {
return apc_delete($key);
}
}
class PhpFileCache implements PhpCacheInterface {
private $_cache_dir;
public function __construct($cache_dir) {
if (is_dir($cache_dir) && is_writable($cache_dir)) {
if (!substr($cache_dir, -1) !== '/') {
$cache_dir .= '/';
}
$this->_cache_dir = $cache_dir;
}
else {
throw new \Exception('Specified cache dir, ' . $cache_dir . ', is not a writable directory.');
}
}
public function store($key, $data, $ttl = 0) {
$fpath = $this->_cache_dir . $key;
$data = array(
'data' => $data,
'ttl' => $ttl
);
$fp = fopen($fpath, 'w');
fwrite($fp, serialize($data));
fclose($fp);
}
public function fetch($key) {
$fpath = $this->_cache_dir . $key;
if (!file_exists($fpath)) {
return false;
}
$store = unserialize(file_get_contents($fpath));
if (is_array($store) && isset($store['data']) && isset($store['ttl'])) {
if ($store['ttl'] && filemtime($fpath) < time() - $store['ttl']) {
return false;
}
return $store['data'];
}
return false;
}
public function delete($key) {
return unlink($this->_cache_dir . $key);
}
}
?>