_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 Memcached(); if (!$this->_cache->addServer($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 * * @return bool * @throws Exception */ public function set($key, &$value) { $key = $this->cleanKey($key); if (!$this->_cache->set($key, $value, $this->_timeout)) { CRM_Core_Error::debug('Result Code: ', $this->_cache->getResultMessage()); CRM_Core_Error::fatal("memcached set failed, wondering why?, $key", $value); return FALSE; } return TRUE; } /** * @param $key * * @return mixed */ public function &get($key) { $key = $this->cleanKey($key); $result = $this->_cache->get($key); return $result; } /** * @param $key * * @return mixed */ public function delete($key) { $key = $this->cleanKey($key); return $this->_cache->delete($key); } /** * @param $key * * @return mixed|string */ public function cleanKey($key) { $key = preg_replace('/\s+|\W+/', '_', $this->_prefix . $key); if (strlen($key) > self::MAX_KEY_LEN) { $md5Key = md5($key); // this should be 32 characters in length $subKeyLen = self::MAX_KEY_LEN - 1 - strlen($md5Key); $key = substr($key, 0, $subKeyLen) . "_" . $md5Key; } return $key; } /** * @return mixed */ public function flush() { return $this->_cache->flush(); } }