Skip to content

Instantly share code, notes, and snippets.

@polonskiy
Created January 28, 2014 13:27
Show Gist options
  • Save polonskiy/8667573 to your computer and use it in GitHub Desktop.
Save polonskiy/8667573 to your computer and use it in GitHub Desktop.
FileSystem Storage Concept
<?php
class FSStorage {
protected $dir;
public function __construct($dir) {
$this->dir = $dir;
}
public function set($key, $data) {
$path = $this->getPath($key);
$dir = dirname($path);
if (!is_dir($dir)) mkdir($dir, 0700, true);
file_put_contents($path, $data, LOCK_EX);
clearstatcache();
}
public function get($key, $ttl = 0) {
$path = $this->getPath($key);
if (!is_file($path)) return null;
$mtime = filemtime($path);
if ($ttl && ($mtime + $ttl) < time()) return null;
$f = fopen($path, 'rb');
flock($f, LOCK_SH);
$data = fread($f, filesize($path));
flock($f, LOCK_UN);
return $data;
}
protected function getPath($key) {
$hash = md5($key);
$parts = array_slice(str_split($hash, 2), 0, 4);
$path = rtrim($this->dir, '/') . '/'
$path .= implode('/', $parts);
$path .= "/$hash";
return $path;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment