-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcache.php
More file actions
54 lines (45 loc) · 1.38 KB
/
cache.php
File metadata and controls
54 lines (45 loc) · 1.38 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
<?php
use Predis\Client;
class Cache {
public $redis;
public $default_max_age;
public function __construct() {
$this->redis = new Predis\Client(getenv('REDIS_URL'));
$this->default_max_age = getenv("MAX_CACHE_AGE");
}
public function add($key, $value) {
$val = [time(), $value];
$json_blob = json_encode($val);
$this->redis->set($key, $json_blob);
}
public function existsNoOlderThan($key, $max_age) {
if ($max_age < 0) {
$max_age=$this->default_max_age;
}
$now = time();
if ($this->redis->exists($key)) {
$json_blob = $this->redis->get($key);
$val = json_decode($json_blob, true);
$age = $now - $val[0];
if ($age < $max_age) {
return true;
}
}
return false;
}
public function get($key, $callable, $max_age=-1) {
if ($max_age < 0) {
$max_age=$this->default_max_age;
}
if ($this->existsNoOlderThan($key, $max_age)) {
$json_blob = $this->redis->get($key);
$val = json_decode($json_blob, true);
//error_log("cache hit for $key");
return $val[1];
}
//error_log("cache missed for $key");
$new_val = $callable();
$this->add($key, $new_val);
return $new_val;
}
}