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;
19 use TraitMemcacheCommand;
27 * @var LoggerInterface
32 * Due to limitations of the INI format, the expected configuration for Memcached servers is the following:
34 * 0 => "hostname, port(, weight)",
38 * @param array $memcached_hosts
42 public function __construct(string $hostname, Configuration $config, LoggerInterface $logger)
44 if (!class_exists('Memcached', false)) {
45 throw new Exception('Memcached class isn\'t available');
48 parent::__construct($hostname);
50 $this->logger = $logger;
52 $this->memcached = new Memcached();
54 $memcached_hosts = $config->get('system', 'memcached_hosts');
56 array_walk($memcached_hosts, function (&$value) {
57 if (is_string($value)) {
58 $value = array_map('trim', explode(',', $value));
62 $this->server = $memcached_hosts[0][0] ?? 'localhost';
63 $this->port = $memcached_hosts[0][1] ?? 11211;
65 $this->memcached->addServers($memcached_hosts);
67 if (count($this->memcached->getServerList()) == 0) {
68 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
75 public function getAllKeys($prefix = null)
77 $keys = $this->getOriginalKeys($this->getMemcacheKeys());
79 return $this->filterArrayKeysByPrefix($keys, $prefix);
85 public function get($key)
88 $cachekey = $this->getCacheKey($key);
90 // We fetch with the hostname as key to avoid problems with other applications
91 $value = $this->memcached->get($cachekey);
93 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
96 $this->logger->debug('Memcached \'get\' failed', ['result' => $this->memcached->getResultMessage()]);
105 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
107 $cachekey = $this->getCacheKey($key);
109 // We store with the hostname as key to avoid problems with other applications
111 return $this->memcached->set(
117 return $this->memcached->set(
127 public function delete($key)
129 $cachekey = $this->getCacheKey($key);
130 return $this->memcached->delete($cachekey);
136 public function clear($outdated = true)
141 return $this->memcached->flush();
148 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
150 $cachekey = $this->getCacheKey($key);
151 return $this->memcached->add($cachekey, $value, $ttl);
157 public function getName()
159 return self::TYPE_MEMCACHED;