缓存readdir() [英] Caching readdir()
本文介绍了缓存readdir()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否仍然要缓存readdir()结果?现在,每次我在网站上输入特定网页时,我都会在目录树上执行readdir().
Is there anyway to cache readdir() result? Right now I do readdir() on a directory tree everytime I enter a specific webpage on the website.
更新:
- 所有用户的目录结构相同.
- 不幸的是,我的共享主机不支持APC或内存缓存:-(
推荐答案
您可以将Memcache
与filemtime
$path = __DIR__ . "/test";
$cache = new Memcache();
$cache->addserver("localhost");
$key = sha1($path);
$info = $cache->get(sha1($path));
if ($info && $info->time == filemtime($path)) {
echo "Cache Copy ", date("Y-m-d g:i:s", $info->time);
} else {
$info = new stdClass();
$info->readDir = array_map("strval", iterator_to_array(new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS)));
$info->time = filemtime($path);
$cache->set($key, $info, MEMCACHE_COMPRESSED, 0);
echo "Path Changed ", date("Y-m-d g:i:s", $info->time);
}
var_dump(array_values($info->readDir));
更新
不幸的是,我的共享主机不支持APC或内存缓存:-(
Unfortunately my shared host do not support APC or memcache :-(
您可以使用文件系统
$path = __DIR__ . "/test";
$cache = new MyCache(__DIR__ . "/a");
$key = sha1($path);
$info = $cache->get($key);
if ($info && $info->time == filemtime($path)) {
echo "Cache Copy ", date("Y-m-d g:i:s", $info->time);
} else {
$info = new stdClass();
$info->readDir = array_map("strval", iterator_to_array(new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS)));
$info->time = filemtime($path);
$cache->set($key, $info, MEMCACHE_COMPRESSED, 0);
echo "Path Changed ", date("Y-m-d g:i:s", $info->time);
}
var_dump(array_values((array) $info->readDir));
使用的类
class MyCache {
private $path;
function __construct($path) {
is_writable($path) or trigger_error("Path Not Writeable");
is_dir($path) or trigger_error("Path Not a Directory");
$this->path = $path;
}
function get($key) {
$file = $this->path . DIRECTORY_SEPARATOR . $key . ".cache";
if (! is_file($file))
return false;
$data = file_get_contents($file);
substr($data, 0, 2) == "##" and $data = gzinflate(substr($data, 2));
return json_decode($data);
}
function set($key, $value, $compression = 0) {
$data = json_encode($value);
$compression and $data = gzdeflate($data, 9) and $data = "##" . $data;
return file_put_contents($this->path . DIRECTORY_SEPARATOR . $key . ".cache", $data);
}
}
这篇关于缓存readdir()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文