Skip to content

Instantly share code, notes, and snippets.

@aknosis
Created September 2, 2011 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aknosis/1189222 to your computer and use it in GitHub Desktop.
Save aknosis/1189222 to your computer and use it in GitHub Desktop.
Simple File Based Cache Mechanism in PHP
<?php
/**
* @param string $uniqID - Anything that would be unique to what you are caching (url/database query)
* @param integer $expireSeconds - How old is too old that we refresh the cache
*/
function _getFromCache($uniqID,$expireSeconds){
$uniq = '/<path to your cache storage folder>/'.md5($uniqID);
if(file_exists($uniq) && time() - filemtime($uniq) <= $expireSeconds){
return '<process cached file>($uniq)';
}
$somethingToCache = '<standard execution to get item>($uniqID)';
file_put_contents($uniq,$somethingToCache); //You will want to implement __toString() if this is an object or maybe you can just serialize it
return $somethingToCache;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment