Created
June 29, 2017 03:49
-
-
Save rming/54de3b63f9dcc824b1070f3136fcf4e0 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 fileCacheHandler | |
{ | |
private static $_instance = null; | |
private static $cacheDir = "/dev/shm/cache_file/"; | |
public static function getInstance() | |
{ | |
if (!static::$_instance) { | |
static::$_instance = new static; | |
} | |
if(!is_dir(static::$cacheDir)){ | |
mkdir(static::$cacheDir,0777); | |
} | |
return static::$_instance; | |
} | |
public function set($k, $v) | |
{ | |
$cacheFile = static::$cacheDir.$k; | |
return file_put_contents($cacheFile, $v); | |
} | |
public function get($k) | |
{ | |
$cacheFile = static::$cacheDir.$k; | |
clearstatcache(true, $cacheFile); | |
$mtime = filemtime($cacheFile); | |
if (time() > intval($mtime)) { | |
return false; | |
} | |
return file_get_contents($cacheFile); | |
} | |
public function expire($k, $expiresAfter = 300) | |
{ | |
$cacheFile = static::$cacheDir.$k; | |
return touch($cacheFile, time() + $expiresAfter); | |
} | |
public function clearCache() | |
{ | |
$res = true; | |
$files = array_diff(scandir(static::$cacheDir), array('.','..')); | |
foreach ($files as $file) { | |
$f = sprintf('%s/%s', static::$cacheDir, $file); | |
$res = $res && (is_file($f) ? unlink($f) : false); | |
} | |
return $res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment