-
-
Save krciga22/b82b21428dc2c9a9b440 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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