From 75359bc11b02f888512be2e29c566e48456d1240 Mon Sep 17 00:00:00 2001 From: Eugene Molotov Date: Fri, 3 May 2019 14:56:07 +0500 Subject: [PATCH] [core] Implemented MemcachedCache (#1000) * [core] Implemented MemcachedCache --- caches/MemcachedCache.php | 115 ++++++++++++++++++++++++++++++++++++++ config.default.ini.php | 4 ++ 2 files changed, 119 insertions(+) create mode 100644 caches/MemcachedCache.php diff --git a/caches/MemcachedCache.php b/caches/MemcachedCache.php new file mode 100644 index 00000000..42291790 --- /dev/null +++ b/caches/MemcachedCache.php @@ -0,0 +1,115 @@ + 65535) { + returnServerError('"port" param is invalid for ' . get_called_class() . '. Please check your config.ini.php'); + } + + $conn = new Memcached(); + $conn->addServer($host, $port) or returnServerError('Could not connect to memcached server'); + $this->conn = $conn; + } + + public function loadData(){ + if ($this->data) return $this->data; + $result = $this->conn->get($this->getCacheKey()); + if ($result === false) { + return false; + } + + $this->time = $result['time']; + $this->data = $result['data']; + return $result['data']; + } + + public function saveData($datas){ + $time = time(); + $object_to_save = array( + 'data' => $datas, + 'time' => $time, + ); + $result = $this->conn->set($this->getCacheKey(), $object_to_save, $this->expiration); + + if($result === false) { + returnServerError('Cannot write the cache to memcached server'); + } + + $this->time = $time; + + return $this; + } + + public function getTime(){ + if ($this->time === false) { + $this->loadData(); + } + return $this->time; + } + + public function purgeCache($duration){ + // Note: does not purges cache right now + // Just sets cache expiration and leave cache purging for memcached itself + $this->expiration = $duration; + } + + /** + * Set scope + * @return self + */ + public function setScope($scope){ + $this->scope = $scope; + return $this; + } + + /** + * Set key + * @return self + */ + public function setKey($key){ + if (!empty($key) && is_array($key)) { + $key = array_map('strtolower', $key); + } + $key = json_encode($key); + + if (!is_string($key)) { + throw new \Exception('The given key is invalid!'); + } + + $this->key = $key; + return $this; + } + + private function getCacheKey(){ + if(is_null($this->key)) { + returnServerError('Call "setKey" first!'); + } + + return 'rss_bridge_cache_' . hash('md5', $this->scope . $this->key . 'A'); + } +} diff --git a/config.default.ini.php b/config.default.ini.php index 90498230..5f4a75f6 100644 --- a/config.default.ini.php +++ b/config.default.ini.php @@ -57,3 +57,7 @@ password = "" [SQLiteCache] file = "cache.sqlite" + +[MemcachedCache] +host = "localhost" +port = 11211