readdir()の結果をキャッシュする方法はありますか?現在、Webサイトの特定のWebページに入るたびに、ディレクトリツリーでreaddir()を実行しています。
アップデート:
- ディレクトリ構造はすべてのユーザーで同じです。
- 残念ながら、私の共有ホストはAPCまたはmemcacheをサポートしていません:-(
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);
}
}
セッションを開始する場合は、セッション変数に保存できます。session_start()関数などを見てください。
いくつかの方法を使用して、シリアル化可能なPHP構造をキャッシュできます。最近、PHPにはAPCが付属しているので、APCオブジェクトのキャッシュを検討することをお勧めします。
http://uk1.php.net/manual/en/ref.apc.php
ディレクトリ構造が変更されたときにキャッシュをクリアするためのロジックがあることを確認してください。