首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >缓存readdir()

缓存readdir()
EN

Stack Overflow用户
提问于 2012-11-29 09:33:37
回答 3查看 606关注 0票数 0

是否存在缓存readdir()结果的方法?现在,每当我在网站上输入特定的网页时,我都会在目录树上做readdir()。

更新:

  • 目录结构对所有用户都是相同的。
  • 不幸的是,我的共享主机不支持APC或memcache :-(
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-11-29 10:06:35

您可以将Memcachefilemtime结合使用

代码语言:javascript
复制
$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或memcache :-(

您可以使用文件系统

代码语言:javascript
复制
$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));

使用的类

代码语言:javascript
复制
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);
    }
}
票数 1
EN

Stack Overflow用户

发布于 2012-11-29 09:36:54

如果启动会话,可以将其存储在会话变量中。查看session_start()函数,等等。

票数 0
EN

Stack Overflow用户

发布于 2012-11-29 09:38:25

您可以使用许多方法缓存任何可序列化的PHP结构。现在PHP随APC一起发布了,所以我建议考虑APC对象缓存。

http://uk1.php.net/manual/en/ref.apc.php

当目录结构发生变化时,一定要有一些逻辑来清除缓存。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13622677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档