Skip to content

Instantly share code, notes, and snippets.

@Casperhr
Created July 23, 2015 08:15
Show Gist options
  • Select an option

  • Save Casperhr/68f5dabbca7a60d65157 to your computer and use it in GitHub Desktop.

Select an option

Save Casperhr/68f5dabbca7a60d65157 to your computer and use it in GitHub Desktop.
<?php
namespace Puzz\Core;
use Illuminate\Support\Facades\Cache;
use Nodes\Exception\Exception;
/**
* Class CacheHelper
* @author cr@nodes.dk
*
* @package Puzz\Core
*/
class CacheHelper
{
/**
* Get the cache by configkey set in crowdit.php in config and params
* @author cr@nodes.dk
* @param $configKey
* @param $params, string or array
* @return mixed
*/
public static function get($configKey, $params) {
$config = self::getCacheConfig($configKey);
if(!config('puzz.cache.active') || !$config['active']) {
return false;
}
$cacheKey = self::generateCacheKey($config, $params);
return Cache::get($cacheKey, false);
}
/**
* Set the cache by configkey set in puzz.php in config, params and data
*
* @author cr@nodes.dk
* @param $configKey
* @param $params
* @param $data
* @return mixed
* @throws Exception
*/
public static function put($configKey, $params, $data) {
$config = self::getCacheConfig($configKey);
if(!config('puzz.cache.active') || !$config['active']) {
return false;
}
$cacheKey = self::generateCacheKey($config, $params);
return Cache::put($cacheKey, $data, $config['time']);
}
/**
* @author cr@nodes.dk
* @param $configKey
* @return mixed
* @throws Exception
*/
public static function getCacheConfig($configKey) {
$config = config('puzz.cache.' . $configKey);
if(empty($config)) {
throw new Exception('Config: ' . $configKey . ' was not found');
}
return $config;
}
/**
* Will generate a cache key from config and params
*
* @author cr@nodes.dk
* @param $config
* @param $params string or array
* @return string
*/
public static function generateCacheKey($config, $params) {
if(is_array($params)) {
//Sort the array so they always are in same order
asort($params);
// Build string
$params = http_build_query($params);
}
return $config['key'] . $params;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment