Skip to content

Instantly share code, notes, and snippets.

@EugeneCib
Last active August 29, 2015 14:26
Show Gist options
  • Save EugeneCib/c516556ec6e47b0b2408 to your computer and use it in GitHub Desktop.
Save EugeneCib/c516556ec6e47b0b2408 to your computer and use it in GitHub Desktop.
Twig + PHP static page caching example. Caching based on unique URL
<?php
// CONFIG
define("DEBUG", true);
define("CACHE", false);
define("CACHE_TIME", 86400);
define("CACHE_GZ_HANDLER", true);
define("BASE_DIR", __DIR__);
define("CACHE_DIR", BASE_DIR.'/cache/');
define("SITE_URL", 'http://' . $_SERVER['HTTP_HOST'] );
// . $_SERVER['QUERY_STRING']); // In this page we don't use query string
// strtok don't use part ? in url
define("DYNAMIC_URL", SITE_URL . strtok($_SERVER["REQUEST_URI"],'?'));
/*
.
.
.
*/
// GET FROM CACHE PART
if(!DEBUG && CACHE)
{
$cache_file = CACHE_DIR . md5( DYNAMIC_URL ).'.html';
if(file_exists($cache_file) && (time() - CACHE_TIME < filemtime($cache_file)))
{
ob_start(CACHE_GZ_HANDLER ? 'ob_gzhandler' : null);
readfile($cache_file);
ob_end_flush();
exit();
}
}
else
{
$files = glob(CACHE_DIR . '*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
{
unlink($file); // delete file
}
}
}
/*
.
.
.
*/
// Create cache
$html = $twig->render($template, $context);
if(!DEBUG && CACHE)
{
$cache_file = CACHE_DIR . md5( DYNAMIC_URL ).'.html';
$fp = fopen( $cache_file, 'w' );
fwrite( $fp, $html );
fclose( $fp );
}
echo $html; // output html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment