add redis cache storage
[pharext/pharext.org] / app / Github / Storage / Redis.php
1 <?php
2
3 namespace app\Github\Storage;
4
5 use app\Github\Storage;
6
7 class Redis implements Storage
8 {
9 private $rd;
10 private $ns;
11
12 function __construct($ns = "github", \Redis $rd = null) {
13 $this->ns = $ns;
14 if (!$rd) {
15 $rd = new \Redis();
16 $rd->open("localhost");
17 $rd->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
18 }
19 $this->rd = $rd;
20 }
21
22 private function key($key) {
23 return sprintf("%s:%s", $this->ns, $key);
24 }
25
26 function get($key, &$val = null, &$ltl = null, $update = false) {
27 if (!$item = $this->rd->get($this->key($key))) {
28 header("Cache-Item: ".serialize($item), false);
29 return false;
30 }
31
32 $val = $item->value;
33 $ttl = $item->ttl;
34 $set = $item->time;
35
36 if (!isset($ttl)) {
37 return true;
38 }
39 $now = time();
40 $ltl = $ttl - ($now - $set);
41 header("X-Cache-Times: ltl=$ltl,now=$now,set=$set,ttl=$ttl", false);
42 if ($ltl >= 0) {
43 if ($update) {
44 $item->time = time();
45 $this->rd->setex($this->key($key), $ttl + 60*60*24, $item);
46 }
47 return true;
48 }
49 return false;
50 }
51
52 function set($key, $val, $ttl = null) {
53 $item = new Redis\Item([
54 "value" => $val,
55 "ttl" => $ttl,
56 "time" => isset($ttl) ? time() : null
57 ]);
58 if (isset($ttl)) {
59 $this->rd->set($this->key($key), $item);
60 } else {
61 $this->rd->setex($this->key($key), $ttl + 60*60*24, $item);
62 }
63 return $this;
64 }
65
66 function del($key) {
67 $this->rd->delete($this->key($key));
68 }
69 }
70
71 namespace app\Github\Storage\Redis;
72
73 class Item
74 {
75 public $value;
76 public $time;
77 public $ttl;
78
79 function __construct(array $data) {
80 foreach ($data as $key => $val) {
81 $this->$key = $val;
82 }
83 }
84 }
85