Skip to content

Instantly share code, notes, and snippets.

@bg5sbk
Created December 8, 2013 08:29
Show Gist options
  • Save bg5sbk/7854636 to your computer and use it in GitHub Desktop.
Save bg5sbk/7854636 to your computer and use it in GitHub Desktop.
A file system based cache class.
<?php
class file_cache
{
private $root_dir;
public function __construct($root_dir) {
$this->root_dir = $root_dir;
if (FALSE == file_exists($this->root_dir)) {
mkdir($this->root_dir, 0700, true);
}
}
public function set($key, $value) {
$key = $this->escape_key($key);
$file_name = $this->root_dir . '/' . $key;
$dir = dirname($file_name);
if (FALSE == file_exists($dir)) {
mkdir($dir, 0700, true);
}
file_put_contents($file_name, serialize($value), LOCK_EX);
}
public function get($key) {
$key = $this->escape_key($key);
$file_name = $this->root_dir . '/' . $key;
if (file_exists($file_name)) {
return unserialize(file_get_contents($file_name));
}
return null;
}
public function remove($key) {
$key = $this->escape_key($key);
$file = $this->root_dir . '/' . $key;
if (file_exists($file)) {
unlink($file);
}
}
public function remove_by_search($key) {
$key = $this->escape_key($key);
$dir = $this->root_dir . '/' . $key;
if (strrpos($key, '/') < 0)
$key .= '/';
if (file_exists($dir)) {
$this->remove_dir($dir);
}
}
private function escape_key($key) {
return str_replace('..', '', $key);
}
private function remove_dir($dirName) {
$result = false;
$handle = opendir($dirName);
while(($file = readdir($handle)) !== false) {
if($file != '.' && $file != '..') {
$dir = $dirName . DIRECTORY_SEPARATOR . $file;
is_dir($dir) ? $this->remove_dir($dir) : unlink($dir);
}
}
closedir($handle);
rmdir($dirName) ? true : false;
return $result;
}
}
?>
@bg5sbk
Copy link
Author

bg5sbk commented Dec 8, 2013

Example, cache in "/dev/shm":

$data_1 = array(
  'u_id' => 1,
  'name' => 'DaDa'
);

$data_2 = array(
  'u_id' => 2,
  'name' => 'WaWa'
);

$cache = new file_cache("/dev/shm");

$cache->set("user/1/data", $data_1);
$cache->set("user/2/data", $data_2);

$result = $cache->get("user/1/data");

$cache->remove("user/1/data");

$cache->remove_by_search("user", $data_1);  // remove all data under 'user' node

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment