_host = $config['host']; } if (isset($config['port'])) { $this->_port = $config['port']; } if (isset($config['timeout'])) { $this->_timeout = $config['timeout']; } if (isset($config['prefix'])) { $this->_prefix = $config['prefix']; } $this->_cache = new Memcache(); if (!$this->_cache->connect($this->_host, $this->_port)) { // dont use fatal here since we can go in an infinite loop echo 'Could not connect to Memcached server'; CRM_Utils_System::civiExit(); } } /** * @param $key * @param $value * @param null|int|\DateInterval $ttl * * @return bool */ public function set($key, $value, $ttl = NULL) { CRM_Utils_Cache::assertValidKey($key); if (is_int($ttl) && $ttl <= 0) { return $this->delete($key); } $expires = CRM_Utils_Date::convertCacheTtlToExpires($ttl, $this->_timeout); return $this->_cache->set($this->getTruePrefix() . $key, serialize($value), FALSE, $expires); } /** * @param $key * @param mixed $default * * @return mixed */ public function get($key, $default = NULL) { CRM_Utils_Cache::assertValidKey($key); $result = $this->_cache->get($this->getTruePrefix() . $key); return ($result === FALSE) ? $default : unserialize($result); } /** * @param string $key * * @return bool * @throws \Psr\SimpleCache\CacheException */ public function has($key) { CRM_Utils_Cache::assertValidKey($key); $result = $this->_cache->get($this->getTruePrefix() . $key); return ($result !== FALSE); } /** * @param $key * * @return bool */ public function delete($key) { CRM_Utils_Cache::assertValidKey($key); $this->_cache->delete($this->getTruePrefix() . $key); return TRUE; } /** * @return bool */ public function flush() { $this->_truePrefix = NULL; $this->_cache->delete($this->_prefix); return TRUE; } public function clear() { return $this->flush(); } protected function getTruePrefix() { if ($this->_truePrefix === NULL || $this->_truePrefix['expires'] < time()) { $key = $this->_prefix; $value = $this->_cache->get($key); if ($value === FALSE) { $value = uniqid(); $this->_cache->set($key, $value, FALSE, 0); // Indefinite. } $this->_truePrefix = [ 'value' => $value, 'expires' => time() + self::NS_LOCAL_TTL, ]; } return $this->_prefix . $this->_truePrefix['value'] . '/'; } }