Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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