From f311fb8083717080622eb0cf9b210b5012d83be1 Mon Sep 17 00:00:00 2001 From: LogMANOriginal Date: Sat, 2 Apr 2022 08:15:28 +0200 Subject: [PATCH] [BridgeAbstract] Add loadCacheValue() and saveCacheValue() (#1380) * [BridgeAbstract] Add loadCacheValue() and saveCacheValue() Bridges currently need to implement value caching manually, which results in duplicate code and more complex bridges. This commit adds two protected functions to BridgeAbstract that make it possible for bridges to store and retrieve values from a temporary cache by key. Co-Authored-By: Roliga Co-authored-by: Roliga --- lib/BridgeAbstract.php | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/lib/BridgeAbstract.php b/lib/BridgeAbstract.php index 917f5fec..82f866aa 100644 --- a/lib/BridgeAbstract.php +++ b/lib/BridgeAbstract.php @@ -370,4 +370,37 @@ abstract class BridgeAbstract implements BridgeInterface { return null; } } + + /** + * Loads a cached value for the specified key + * + * @param string $key Key name + * @param int $duration Cache duration (optional, default: 24 hours) + * @return mixed Cached value or null if the key doesn't exist or has expired + */ + protected function loadCacheValue($key, $duration = 86400){ + $cacheFac = new CacheFactory(); + $cacheFac->setWorkingDir(PATH_LIB_CACHES); + $cache = $cacheFac->create(Configuration::getConfig('cache', 'type')); + $cache->setScope(get_called_class()); + $cache->setKey($key); + if($cache->getTime() < time() - $duration) + return null; + return $cache->loadData(); + } + + /** + * Stores a value to cache with the specified key + * + * @param string $key Key name + * @param mixed $value Value to cache + */ + protected function saveCacheValue($key, $value){ + $cacheFac = new CacheFactory(); + $cacheFac->setWorkingDir(PATH_LIB_CACHES); + $cache = $cacheFac->create(Configuration::getConfig('cache', 'type')); + $cache->setScope(get_called_class()); + $cache->setKey($key); + $cache->saveData($value); + } }