9d76a75b135e7eb8b794fe99f557a1fcb4e141d2
[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, Item &$item = 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 (null === $item->getTTL()) {
35 return true;
36 }
37 if ($item->getLTL() >= 0) {
38 if ($update) {
39 $item->setTimestamp();
40 $this->mc->set($this->key($key), $item, $item->getTTL() + 60*60*24);
41 }
42 return true;
43 }
44 return false;
45 }
46
47 function set($key, Item $item) {
48 $this->mc->set($this->key($key), $item, (null !== $item->getTTL()) ? $item->getTTL() + 60*60*24 : 0);
49 return $this;
50 }
51
52 function del($key) {
53 $this->mc->delete($this->key($key));
54 }
55 }