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