Php 缓存readdir()

Php 缓存readdir(),php,caching,Php,Caching,是否仍要缓存readdir()结果?现在,每当我在网站上输入特定网页时,我都会在目录树上执行readdir() 更新: 所有用户的目录结构都相同 不幸的是,我的共享主机不支持APC或memcache:-( 如果启动会话,您可以将其存储在会话变量中。请查看session_start()函数等。您可以使用多种方法缓存任何可序列化的PHP结构。PHP最近随APC提供,因此我建议查看APC对象缓存 当目录结构更改时,请确保具有清除缓存的逻辑。您可以将Memcache与filemtime $path

是否仍要缓存readdir()结果?现在,每当我在网站上输入特定网页时,我都会在目录树上执行readdir()

更新:

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

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

您可以使用多种方法缓存任何可序列化的PHP结构。PHP最近随APC提供,因此我建议查看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或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);
    }
}

这将为站点上的每个用户存储相同的数据,并可能涉及不必要地启动会话。dir结构可以在应用程序范围内缓存,除非出于问题中未提及的原因,该目录特定于用户。有关简单文件系统版本,请参阅更新的代码。。。