Merge branch 'master' into develop
[friendica.git/.git] / src / Core / Cache / MemcachedCacheDriver.php
1 <?php\r
2 \r
3 namespace Friendica\Core\Cache;\r
4 \r
5 use Friendica\BaseObject;\r
6 use Friendica\Core\Cache;\r
7 \r
8 /**\r
9  * Memcached Cache Driver\r
10  *\r
11  * @author Hypolite Petovan <mrpetovan@gmail.com>\r
12  */\r
13 class MemcachedCacheDriver extends BaseObject implements ICacheDriver\r
14 {\r
15         /**\r
16          * @var Memcached\r
17          */\r
18         private $memcached;\r
19 \r
20         public function __construct(array $memcached_hosts)\r
21         {\r
22                 if (!class_exists('Memcached', false)) {\r
23                         throw new \Exception('Memcached class isn\'t available');\r
24                 }\r
25 \r
26                 $this->memcached = new \Memcached();\r
27 \r
28                 $this->memcached->addServers($memcached_hosts);\r
29 \r
30                 if (count($this->memcached->getServerList()) == 0) {\r
31                         throw new \Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));\r
32                 }\r
33         }\r
34 \r
35         public function get($key)\r
36         {\r
37                 $return = null;\r
38 \r
39                 // We fetch with the hostname as key to avoid problems with other applications\r
40                 $value = $this->memcached->get(self::getApp()->get_hostname() . ':' . $key);\r
41 \r
42                 if ($this->memcached->getResultCode() === \Memcached::RES_SUCCESS) {\r
43                         $return = $value;\r
44                 }\r
45 \r
46                 return $return;\r
47         }\r
48 \r
49         public function set($key, $value, $duration = Cache::MONTH)\r
50         {\r
51                 // We store with the hostname as key to avoid problems with other applications\r
52                 return $this->memcached->set(\r
53                         self::getApp()->get_hostname() . ":" . $key,\r
54                         $value,\r
55                         time() + $duration\r
56                 );\r
57         }\r
58 \r
59         public function delete($key)\r
60         {\r
61                 return $this->memcached->delete($key);\r
62         }\r
63 \r
64         public function clear()\r
65         {\r
66                 return true;\r
67         }\r
68 }\r