3 namespace Friendica\Core\Cache;
6 use Friendica\Core\Cache;
7 use Friendica\Core\Config\Configuration;
13 * @author Hypolite Petovan <hypolite@mrpetovan.com>
15 class MemcacheCache extends AbstractCache implements IMemoryCache
18 use TraitCompareDelete;
28 public function __construct(string $hostname, Configuration $config)
30 if (!class_exists('Memcache', false)) {
31 throw new Exception('Memcache class isn\'t available');
34 parent::__construct($hostname);
36 $this->memcache = new Memcache();
38 $memcache_host = $config->get('system', 'memcache_host');
39 $memcache_port = $config->get('system', 'memcache_port');
41 if (!$this->memcache->connect($memcache_host, $memcache_port)) {
42 throw new Exception('Expected Memcache server at ' . $memcache_host . ':' . $memcache_port . ' isn\'t available');
49 public function getAllKeys($prefix = null)
52 $allSlabs = $this->memcache->getExtendedStats('slabs');
53 foreach ($allSlabs as $slabs) {
54 foreach (array_keys($slabs) as $slabId) {
55 $cachedump = $this->memcache->getExtendedStats('cachedump', (int)$slabId);
56 foreach ($cachedump as $key => $arrVal) {
57 if (!is_array($arrVal)) {
60 $keys = array_merge($keys, array_keys($arrVal));
65 $keys = $this->getOriginalKeys($keys);
67 return $this->filterArrayKeysByPrefix($keys, $prefix);
73 public function get($key)
76 $cachekey = $this->getCacheKey($key);
78 // We fetch with the hostname as key to avoid problems with other applications
79 $cached = $this->memcache->get($cachekey);
81 // @see http://php.net/manual/en/memcache.get.php#84275
82 if (is_bool($cached) || is_double($cached) || is_long($cached)) {
86 $value = @unserialize($cached);
88 // Only return a value if the serialized value is valid.
89 // We also check if the db entry is a serialized
90 // boolean 'false' value (which we want to return).
91 if ($cached === serialize(false) || $value !== false) {
101 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
103 $cachekey = $this->getCacheKey($key);
105 // We store with the hostname as key to avoid problems with other applications
107 return $this->memcache->set(
114 return $this->memcache->set(
125 public function delete($key)
127 $cachekey = $this->getCacheKey($key);
128 return $this->memcache->delete($cachekey);
134 public function clear($outdated = true)
139 return $this->memcache->flush();
146 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
148 $cachekey = $this->getCacheKey($key);
149 return $this->memcache->add($cachekey, serialize($value), MEMCACHE_COMPRESSED, $ttl);
152 public function __toString()
154 return self::TYPE_MEMCACHE;