3 namespace Friendica\Core\Cache;
6 use Friendica\Core\Config\Configuration;
12 * @author Hypolite Petovan <hypolite@mrpetovan.com>
14 class MemcacheCache extends Cache implements IMemoryCache
17 use TraitCompareDelete;
27 public function __construct(string $hostname, Configuration $config)
29 if (!class_exists('Memcache', false)) {
30 throw new Exception('Memcache class isn\'t available');
33 parent::__construct($hostname);
35 $this->memcache = new Memcache();
37 $memcache_host = $config->get('system', 'memcache_host');
38 $memcache_port = $config->get('system', 'memcache_port');
40 if (!@$this->memcache->connect($memcache_host, $memcache_port)) {
41 throw new Exception('Expected Memcache server at ' . $memcache_host . ':' . $memcache_port . ' isn\'t available');
48 public function getAllKeys($prefix = null)
51 $allSlabs = $this->memcache->getExtendedStats('slabs');
52 foreach ($allSlabs as $slabs) {
53 foreach (array_keys($slabs) as $slabId) {
54 $cachedump = $this->memcache->getExtendedStats('cachedump', (int)$slabId);
55 foreach ($cachedump as $key => $arrVal) {
56 if (!is_array($arrVal)) {
59 $keys = array_merge($keys, array_keys($arrVal));
64 $keys = $this->getOriginalKeys($keys);
66 return $this->filterArrayKeysByPrefix($keys, $prefix);
72 public function get($key)
75 $cachekey = $this->getCacheKey($key);
77 // We fetch with the hostname as key to avoid problems with other applications
78 $cached = $this->memcache->get($cachekey);
80 // @see http://php.net/manual/en/memcache.get.php#84275
81 if (is_bool($cached) || is_double($cached) || is_long($cached)) {
85 $value = @unserialize($cached);
87 // Only return a value if the serialized value is valid.
88 // We also check if the db entry is a serialized
89 // boolean 'false' value (which we want to return).
90 if ($cached === serialize(false) || $value !== false) {
100 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
102 $cachekey = $this->getCacheKey($key);
104 // We store with the hostname as key to avoid problems with other applications
106 return $this->memcache->set(
113 return $this->memcache->set(
124 public function delete($key)
126 $cachekey = $this->getCacheKey($key);
127 return $this->memcache->delete($cachekey);
133 public function clear($outdated = true)
138 return $this->memcache->flush();
145 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
147 $cachekey = $this->getCacheKey($key);
148 return $this->memcache->add($cachekey, serialize($value), MEMCACHE_COMPRESSED, $ttl);
154 public function getName()
156 return self::TYPE_MEMCACHE;