3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
8 use Friendica\Network\HTTPException\InternalServerErrorException;
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();
45 $this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, false);
47 array_walk($memcached_hosts, function (&$value) {
48 if (is_string($value)) {
49 $value = array_map('trim', explode(',', $value));
53 $this->memcached->addServers($memcached_hosts);
55 if (count($this->memcached->getServerList()) == 0) {
56 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
63 public function getAllKeys($prefix = null)
65 // Doesn't work because of https://github.com/php-memcached-dev/php-memcached/issues/367
66 // returns everytime an empty array
67 throw new InternalServerErrorException('getAllKeys for Memcached not supported yet');
69 $list = $this->getOriginalKeys($this->memcached->getAllKeys());
71 return $this->filterPrefix($list, $prefix);
77 public function get($key)
80 $cachekey = $this->getCacheKey($key);
82 // We fetch with the hostname as key to avoid problems with other applications
83 $value = $this->memcached->get($cachekey);
85 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
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(
118 public function delete($key)
120 $cachekey = $this->getCacheKey($key);
121 return $this->memcached->delete($cachekey);
127 public function clear($outdated = true)
132 return $this->memcached->flush();
139 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
141 $cachekey = $this->getCacheKey($key);
142 return $this->memcached->add($cachekey, $value, $ttl);