3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
6 use Friendica\Core\Logger;
12 * Memcached Cache Driver
14 * @author Hypolite Petovan <hypolite@mrpetovan.com>
16 class MemcachedCacheDriver extends AbstractCacheDriver implements IMemoryCacheDriver
19 use TraitCompareDelete;
27 * Due to limitations of the INI format, the expected configuration for Memcached servers is the following:
29 * 0 => "hostname, port(, weight)",
33 * @param array $memcached_hosts
36 public function __construct(array $memcached_hosts)
38 if (!class_exists('Memcached', false)) {
39 throw new Exception('Memcached class isn\'t available');
42 $this->memcached = new Memcached();
44 array_walk($memcached_hosts, function (&$value) {
45 if (is_string($value)) {
46 $value = array_map('trim', explode(',', $value));
50 $this->memcached->addServers($memcached_hosts);
52 if (count($this->memcached->getServerList()) == 0) {
53 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
60 public function getAllKeys($prefix = null)
62 $keys = $this->getOriginalKeys($this->memcached->getAllKeys());
64 if ($this->memcached->getResultCode() == Memcached::RES_SUCCESS) {
65 return $this->filterArrayKeysByPrefix($keys, $prefix);
67 Logger::log('Memcached \'getAllKeys\' failed with ' . $this->memcached->getResultMessage(), Logger::ALL);
75 public function get($key)
78 $cachekey = $this->getCacheKey($key);
80 // We fetch with the hostname as key to avoid problems with other applications
81 $value = $this->memcached->get($cachekey);
83 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
86 Logger::log('Memcached \'get\' failed with ' . $this->memcached->getResultMessage(), Logger::ALL);
95 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
97 $cachekey = $this->getCacheKey($key);
99 // We store with the hostname as key to avoid problems with other applications
101 return $this->memcached->set(
107 return $this->memcached->set(
117 public function delete($key)
119 $cachekey = $this->getCacheKey($key);
120 return $this->memcached->delete($cachekey);
126 public function clear($outdated = true)
131 return $this->memcached->flush();
138 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
140 $cachekey = $this->getCacheKey($key);
141 return $this->memcached->add($cachekey, $value, $ttl);