1
|
|
|
<?php |
2
|
|
|
namespace DominionEnterprises\Memoize; |
3
|
|
|
|
4
|
|
|
use \Predis\Client; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* A memoizer that caches the results in a redis cache. |
8
|
|
|
*/ |
9
|
|
|
class Predis implements Memoize |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* The predis client |
13
|
|
|
* |
14
|
|
|
* @var \Predis\Client |
15
|
|
|
*/ |
16
|
|
|
private $_client; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Cache refresh |
20
|
|
|
* |
21
|
|
|
* @var boolean |
22
|
|
|
*/ |
23
|
|
|
private $_refresh; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Sets the predis client. |
27
|
|
|
* |
28
|
|
|
* @param \Predis\Client $client The predis client to use |
29
|
|
|
* @param boolean $refresh If true we will always overwrite cache even if it is already set |
30
|
|
|
*/ |
31
|
|
|
public function __construct(Client $client, $refresh = false) |
32
|
|
|
{ |
33
|
|
|
$this->_client = $client; |
34
|
|
|
$this->_refresh = $refresh; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* The value is stored in redis as a json_encoded string, so make sure that the value you return from $compute is json-encodable. |
39
|
|
|
* |
40
|
|
|
* @see Memoize::memoizeCallable |
41
|
|
|
*/ |
42
|
|
|
public function memoizeCallable($key, $compute, $cacheTime = null) |
43
|
|
|
{ |
44
|
|
|
if (!$this->_refresh) { |
45
|
|
|
try { |
46
|
|
|
$cached = $this->_client->get($key); |
47
|
|
|
if ($cached !== null) { |
48
|
|
|
$data = json_decode($cached, true); |
49
|
|
|
return $data['result']; |
50
|
|
|
} |
51
|
|
|
} catch (\Exception $e) { |
52
|
|
|
return call_user_func($compute); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$result = call_user_func($compute); |
57
|
|
|
|
58
|
|
|
$this->_cache($key, json_encode(['result' => $result]), $cacheTime); |
59
|
|
|
|
60
|
|
|
return $result; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Caches the value into redis with errors suppressed. |
65
|
|
|
* |
66
|
|
|
* @param string $key The key. |
67
|
|
|
* @param string $value The value. |
68
|
|
|
* @param int $cacheTime The optional cache time |
69
|
|
|
* @return void |
70
|
|
|
*/ |
71
|
|
|
private function _cache($key, $value, $cacheTime = null) |
72
|
|
|
{ |
73
|
|
|
try { |
74
|
|
|
$this->_client->set($key, $value); |
75
|
|
|
|
76
|
|
|
if ($cacheTime !== null) { |
77
|
|
|
$this->_client->expire($key, $cacheTime); |
78
|
|
|
} |
79
|
|
|
} catch (\Exception $e) { |
80
|
|
|
// We don't want exceptions in accessing the cache to break functionality. The cache should be as transparent as possible. |
81
|
|
|
// If insight is needed into these exceptions, a better way would be by notifying an observer with the errors. |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|