Skip to content

Instantly share code, notes, and snippets.

@krciga22
Forked from johndyer/cache.php
Last active August 29, 2015 14:00
Show Gist options
  • Save krciga22/b82b21428dc2c9a9b440 to your computer and use it in GitHub Desktop.
Save krciga22/b82b21428dc2c9a9b440 to your computer and use it in GitHub Desktop.
<?php
class PHPCache {
protected $path = null;
protected $durationInSeconds = null;
protected $filenamePrefix = null;
protected $disableCacheForAdmin = false;
function __construct ( $path, $filenamePrefix='phpcache-', $durationInSeconds = 60) {
$this->path = $path;
$this->filenamePrefix = $filenamePrefix;
$this->durationInSeconds = $durationInSeconds;
}
function getCacheFilename( $id ){
return $this->path . $this->filenamePrefix . md5($id) . '.cache';
}
function get( $id, $durationInSeconds=false) {
if(!$durationInSeconds){
$durationInSeconds = $this->durationInSeconds;
}
$file = $this->getCacheFilename($id);
if (!$this->disableCacheForAdmin
&& file_exists($file)
&& time() - filemtime($file) < $durationInSeconds) {
return unserialize( file_get_contents($file) );
} else {
return null;
}
}
function set( $id, $obj) {
$file = $this->getCacheFilename($id);
file_put_contents($file, serialize($obj));
}
function disableCacheForAdmin($aUserIsAdminBoolean){
$this->disableCacheForAdmin = $aUserIsAdminBoolean;
}
}
/* example initiation */
$cacheDirectory = 'path-to-your-cache-directory/';
$cache = new PHPCache($cacheDirectory);
$cache->disableCacheForAdmin(checkIfUserIsAdmin());
/* example usage */
$cacheKey = __FILE__;
$cacheDurationInSeconds = 60;
$cachedView = $cache->get($cacheKey, $cacheDurationInSeconds);
if (is_null($cachedView)){
ob_start();
echo "echo out your view here and it will be cached.";
$cachedView = ob_get_contents();
ob_clean();
$cache->set(__FILE__, $cachedView);
}
echo $cachedView;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment