3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
11 * Memcached Cache Driver
13 * @author Hypolite Petovan <mrpetovan@gmail.com>
15 class MemcachedCacheDriver extends AbstractCacheDriver implements IMemoryCacheDriver
18 use TraitCompareDelete;
26 * Due to limitations of the INI format, the expected configuration for Memcached servers is the following:
28 * 0 => "hostname, port(, weight)",
32 * @param array $memcached_hosts
35 public function __construct(array $memcached_hosts)
37 if (!class_exists('Memcached', false)) {
38 throw new Exception('Memcached class isn\'t available');
41 $this->memcached = new Memcached();
43 array_walk($memcached_hosts, function (&$value) {
44 $value = array_map('trim', explode(',', $value));
47 $this->memcached->addServers($memcached_hosts);
49 if (count($this->memcached->getServerList()) == 0) {
50 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
54 public function get($key)
57 $cachekey = $this->getCacheKey($key);
59 // We fetch with the hostname as key to avoid problems with other applications
60 $value = $this->memcached->get($cachekey);
62 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
69 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
71 $cachekey = $this->getCacheKey($key);
73 // We store with the hostname as key to avoid problems with other applications
75 return $this->memcached->set(
81 return $this->memcached->set(
89 public function delete($key)
91 $cachekey = $this->getCacheKey($key);
92 return $this->memcached->delete($cachekey);
95 public function clear($outdated = true)
100 return $this->memcached->flush();
105 * @brief Sets a value if it's not already stored
107 * @param string $key The cache key
108 * @param mixed $value The old value we know from the cache
109 * @param int $ttl The cache lifespan, must be one of the Cache constants
112 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
114 $cachekey = $this->getCacheKey($key);
115 return $this->memcached->add($cachekey, $value, $ttl);