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 if (is_string($value)) {
45 $value = array_map('trim', explode(',', $value));
49 $this->memcached->addServers($memcached_hosts);
51 if (count($this->memcached->getServerList()) == 0) {
52 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
56 public function get($key)
59 $cachekey = $this->getCacheKey($key);
61 // We fetch with the hostname as key to avoid problems with other applications
62 $value = $this->memcached->get($cachekey);
64 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
71 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
73 $cachekey = $this->getCacheKey($key);
75 // We store with the hostname as key to avoid problems with other applications
77 return $this->memcached->set(
83 return $this->memcached->set(
91 public function delete($key)
93 $cachekey = $this->getCacheKey($key);
94 return $this->memcached->delete($cachekey);
97 public function clear($outdated = true)
102 return $this->memcached->flush();
107 * @brief Sets a value if it's not already stored
109 * @param string $key The cache key
110 * @param mixed $value The old value we know from the cache
111 * @param int $ttl The cache lifespan, must be one of the Cache constants
114 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
116 $cachekey = $this->getCacheKey($key);
117 return $this->memcached->add($cachekey, $value, $ttl);