Skip to content

Instantly share code, notes, and snippets.

@allex
Last active September 14, 2015 10:05
Show Gist options
  • Save allex/b3793353690a89452c7f to your computer and use it in GitHub Desktop.
Save allex/b3793353690a89452c7f to your computer and use it in GitHub Desktop.
<?php
namespace app\helpers;
/**
* A simple k/v cache manager based on file system.
*
* @author Allex Wang ([email protected])
*
* GistID: b3793353690a89452c7f
* GistURL: https://gist.github.com/allex/b3793353690a89452c7f
*/
class KVCache {
private static $_instance;
private $cacheDir = null;
private function __construct() {
$dir = rtrim(sys_get_temp_dir(), '/') . DIRECTORY_SEPARATOR . 'php_kvcache' . DIRECTORY_SEPARATOR . ftok(__FILE__, 't');
if (!file_exists($dir) && !mkdir($dir, 0700, true)) {
throw new \Exception("Create cache dir fails: $dir");
}
$this->cacheDir = $dir;
}
public static function getInstance() {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function set($k, $v) {
if (!$this->has($k)) {
return file_put_contents($this->cacheDir . '/' . $k, $v);
}
return FALSE;
}
public function get($k) {
if ($this->has($k)) {
return file_get_contents($this->cacheDir . '/' . $k);
}
return NULL;
}
public function has($k) {
return file_exists($this->cacheDir . '/' . $k);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment