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