Skip to content

Instantly share code, notes, and snippets.

@ursbraem
Last active September 5, 2016 16:02
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 ursbraem/29e3f25268fca0ee585d10ffd0ecad35 to your computer and use it in GitHub Desktop.
Save ursbraem/29e3f25268fca0ee585d10ffd0ecad35 to your computer and use it in GitHub Desktop.
Static file caching for expensive perch queries
<?php
// layout to prepend to restricted pages
$Users = new PerchUsers;
$CurrentUser = $Users->get_current_user();
if (!(is_object($CurrentUser) && $CurrentUser->logged_in())) {
// user is not logged in to Perch
exit('Please log in first.');
}
// Note:
// if ($CurrentUser->userMasterAdmin()){
// // user is the *primary* admin
// }
<?php
// layout to include where needed
// helper function for caching
function sanitizeStringForFilename($string){
// sanitize string for filename http://stackoverflow.com/a/2021729/160968
$r = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $string);
$r = mb_ereg_replace("([\.]{2,})", '', $r);
return $r;
}
/*
* Helper function to save static copy of any string
* manually make sure that the id of the file is unique!
* @param $content string
* @param $id string
*/
function saveStaticCopy($content,$id){
$id = sanitizeStringForFilename($id);
$cacheFile = PATH_TO_CACHE_DIR_WITH_ENDING_SLASH . $id . '.txt';
file_put_contents($cacheFile,$content);
return false;
}
/*
* Helper function to read static copy of any string
* @param $id string
* @param $maxAgeHours int
*/
function loadStaticCopy($id,$maxAgeHours){
$id = sanitizeStringForFilename($id);
$cacheFile = PATH_TO_CACHE_DIR_WITH_ENDING_SLASH . $id . '.txt';
if (file_exists($cacheFile)) {
$cacheFileModificationTime = filemtime($cacheFile);
$now = time();
$maxAge = $maxAgeHours * 60 * 60;
if (($now - $cacheFileModificationTime) < $maxAge) {
return file_get_contents($cacheFile);
}
// file is too old
return false;
}
// file does not exist
return false;
}
<?php
perch_layout('helpers');
$cachingId = 'somedynamicallycreatedvalue';
$cachedContent = loadStaticCopy($cachingId,24); // returns false if inexistant or older than maxAgeHours
// output the content regularly
if (!empty($cachedContent)){
echo $cachedContent;
}
else {
// output what we've got already
PerchUtil::flush_output();
// render list
$r = perch_collection('Things', [
// options
},
], true);
saveStaticCopy($r,$cachingId);
echo $r;
}
<?php
// external users can't access this page
perch_layout('adminlogin');
// clear /cache/ folder
$files = glob(PATH_TO_CACHE_DIR_WITH_ENDING_SLASH.'*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file)){
unlink($file); // delete file
}
}
die('ok! Cache cleared.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment