Skip to content

Instantly share code, notes, and snippets.

@skhani
Created December 4, 2014 17:40
Show Gist options
  • Save skhani/ff9f995f186ec1be7051 to your computer and use it in GitHub Desktop.
Save skhani/ff9f995f186ec1be7051 to your computer and use it in GitHub Desktop.
Cache function
<?php
class Cache
{
public static $extension = NULL;
public static $location = NULL;
public static $memcached = NULL;
public static $port = NULL;
public static $time = 0;
public static $type = NULL;
/**
* The constructor for the Cache class.
* @access Public
* @since 1.0.0
* @param string [$type] The type of caching method to use, either 'file' or 'memcached'
* @param int [$time] How many seconds until cache files are considered cold
* @param string [$location] The absolute path of the cache directory (file) or host (memcached)
* @param string [$extension] The file extension for cache items (file only)
* @param int [$port] The port to use (Memcached only)
*/
public function __construct($type = 'file', $time = 600, $location, $extension = '.c', $port = 11211)
{
if(strtolower($type) == 'file')
{
$type = 'file';
} else if(strtolower($type) == 'memcache' || strtolower($type) == 'memcached') {
$type = 'memcached';
$memcached = new Memcached();
$memcached->addServer($location, $port);
self::$memcached = $memcached;
} else {
$type = FALSE;
}
self::$extension = $extension;
self::$location = $location;
self::$port = $port;
self::$time = $time;
self::$type = $type;
}
/**
* Retrieves any valid cached data.
* @access Public
* @since 1.0.1
* @param string [$key] The cache file key
* @return mixed The cached data if valid, otherwise FALSE
*/
public function get($key)
{
if(self::$type == 'file')
{
$file = self::$location . md5($key) . self::$extension;
if(file_exists($file) && is_readable($file))
{
if((time() - filemtime($file)) <= self::$time)
{
return file_get_contents($file);
}
}
return FALSE;
} else if(self::$type == 'memcached') {
$data = self::$memcached->get($key);
if(self::$memcached->getResultCode() == Memcached::RES_SUCCESS)
{
return $data;
}
} else {
return FALSE;
}
}
/**
* Creates a cache of data.
* @access Public
* @since 1.0.0
* @param string [$key] The cache file key
* @param mixed [$data] The data to cache
*/
public function set($key, $data)
{
if(self::$type == 'file')
{
$file = self::$location . md5($key) . self::$extension;
if(is_writable(self::$location))
{
$handle = fopen($file, 'w');
fwrite($handle, json_encode($data));
fclose($handle);
}
} else if(self::$type == 'memcached') {
self::$memcached->set($key, $data, time() + self::$time);
} else {
return FALSE;
}
}
}
/**
* Implementation
*/
$key = 'blabalbla';
$cacheObj = new Cache('file' , 300 , '/tmp');
$cachedData = $cacheObj->get($key);
if($cachedData !== FALSE){
//use cached data
$data = //cahche content;
}else{
//select the query
// $data = query;
$cacheObj->set($key , $data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment