-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCache.php
86 lines (65 loc) · 2.09 KB
/
Cache.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
<?php
namespace CodeMeme\CacheBundle;
class Cache
{
private $adapter;
public function __construct($adapter = null)
{
$this->adapter = $adapter;
}
public function getAdapter()
{
return $this->adapter;
}
public function setAdapter($adapter)
{
$this->adapter = $adapter;
return $this;
}
public function get($keyOrObject)
{
$key = $this->getKey($keyOrObject);
// Get the expected expiration time
$expiration = $this->adapter->get($this->getExpireKey($key));
// If the key doesn't exist, then that data never expires
// Otherwise, it expires if we're past the expiration date
$isExpired = ($expiration === false)
? false
: $expiration < time();
return $isExpired ? false : $this->adapter->get($key);
}
public function set($keyOrObject, $data, $lifetime = null)
{
$key = $this->getKey($keyOrObject);
$expireKey = $this->getExpireKey($key);
if (null === $lifetime && $keyOrObject instanceof Cacheable) {
$lifetime = $keyOrObject->getCacheLifetime();
}
$this->adapter->set($key, $data);
if ($lifetime) {
$this->adapter->set($expireKey, time() + $lifetime);
}
}
public function delete($keyOrObject)
{
$key = $this->getKey($keyOrObject);
$expireKey = $this->getExpireKey($key);
$this->adapter->delete($key);
$this->adapter->delete($expireKey);
}
public function getKey($keyOrObject)
{
if ($keyOrObject instanceof Cacheable) {
$key = md5(get_class($keyOrObject) . serialize($keyOrObject->getCacheId()));
} else if (is_scalar($keyOrObject)) {
$key = $keyOrObject;
} else {
throw new Exception(get_class($keyOrObject) . ' must implement the "Cacheable" interface');
}
return $key;
}
public function getExpireKey($keyOrObject)
{
return $this->getKey($keyOrObject) . '.expiration';
}
}