3 namespace Friendica\Core\Cache;
5 use Friendica\BaseObject;
6 use Friendica\Core\Cache;
9 * Memcached Cache Driver
11 * @author Hypolite Petovan <mrpetovan@gmail.com>
13 class MemcachedCacheDriver extends BaseObject implements IMemoryCacheDriver
16 use TraitCompareDelete;
23 public function __construct(array $memcached_hosts)
25 if (!class_exists('Memcached', false)) {
26 throw new \Exception('Memcached class isn\'t available');
29 $this->memcached = new \Memcached();
31 $this->memcached->addServers($memcached_hosts);
33 if (count($this->memcached->getServerList()) == 0) {
34 throw new \Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
38 public function get($key)
42 // We fetch with the hostname as key to avoid problems with other applications
43 $value = $this->memcached->get(self::getApp()->get_hostname() . ':' . $key);
45 if ($this->memcached->getResultCode() === \Memcached::RES_SUCCESS) {
52 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
54 // We store with the hostname as key to avoid problems with other applications
56 return $this->memcached->set(
57 self::getApp()->get_hostname() . ':' . $key,
62 return $this->memcached->set(
63 self::getApp()->get_hostname() . ':' . $key,
70 public function delete($key)
72 $return = $this->memcached->delete(self::getApp()->get_hostname() . ':' . $key);
77 public function clear()
83 * @brief Sets a value if it's not already stored
85 * @param string $key The cache key
86 * @param mixed $value The old value we know from the cache
87 * @param int $ttl The cache lifespan, must be one of the Cache constants
90 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
92 return $this->memcached->add(self::getApp()->get_hostname() . ":" . $key, $value, $ttl);