[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 <roliga.here@gmail.com>

Co-authored-by: Roliga <roliga.here@gmail.com>
This commit is contained in:
LogMANOriginal 2022-04-02 08:15:28 +02:00 committed by GitHub
parent 40a4e7b7c2
commit f311fb8083
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 33 additions and 0 deletions

View File

@ -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);
}
}