3 namespace Friendica\Core\Cache;
6 use Friendica\Core\Config\Configuration;
8 use Psr\Log\LoggerInterface;
13 * @author Hypolite Petovan <hypolite@mrpetovan.com>
15 class MemcachedCache extends Cache implements IMemoryCache
18 use TraitCompareDelete;
26 * @var LoggerInterface
31 * Due to limitations of the INI format, the expected configuration for Memcached servers is the following:
33 * 0 => "hostname, port(, weight)",
37 * @param array $memcached_hosts
41 public function __construct(string $hostname, Configuration $config, LoggerInterface $logger)
43 if (!class_exists('Memcached', false)) {
44 throw new Exception('Memcached class isn\'t available');
47 parent::__construct($hostname);
49 $this->logger = $logger;
51 $this->memcached = new Memcached();
53 $memcached_hosts = $config->get('system', 'memcached_hosts');
55 array_walk($memcached_hosts, function (&$value) {
56 if (is_string($value)) {
57 $value = array_map('trim', explode(',', $value));
61 $this->memcached->addServers($memcached_hosts);
63 if (count($this->memcached->getServerList()) == 0) {
64 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
71 public function getAllKeys($prefix = null)
73 $keys = $this->getOriginalKeys($this->memcached->getAllKeys());
75 if ($this->memcached->getResultCode() == Memcached::RES_SUCCESS) {
76 return $this->filterArrayKeysByPrefix($keys, $prefix);
78 $this->logger->debug('Memcached \'getAllKeys\' failed', ['result' => $this->memcached->getResultMessage()]);
86 public function get($key)
89 $cachekey = $this->getCacheKey($key);
91 // We fetch with the hostname as key to avoid problems with other applications
92 $value = $this->memcached->get($cachekey);
94 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
97 $this->logger->debug('Memcached \'get\' failed', ['result' => $this->memcached->getResultMessage()]);
106 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
108 $cachekey = $this->getCacheKey($key);
110 // We store with the hostname as key to avoid problems with other applications
112 return $this->memcached->set(
118 return $this->memcached->set(
128 public function delete($key)
130 $cachekey = $this->getCacheKey($key);
131 return $this->memcached->delete($cachekey);
137 public function clear($outdated = true)
142 return $this->memcached->flush();
149 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
151 $cachekey = $this->getCacheKey($key);
152 return $this->memcached->add($cachekey, $value, $ttl);
158 public function getName()
160 return self::TYPE_MEMCACHED;