反正緩存readdir()的結果嗎?現在我每次進入網站上的特定網頁時,都會在目錄樹上執行readdir()。緩存readdir()
UPDATE:
- 的目錄結構對於所有用戶都是相同的。
- 不幸的是我的共享主機不支持APC或內存緩存:-(
反正緩存readdir()的結果嗎?現在我每次進入網站上的特定網頁時,都會在目錄樹上執行readdir()。緩存readdir()
UPDATE:
您可以使用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或內存緩存:-(
您可以使用文件系統
$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);
}
}
您可以使用多種方法與APC這幾天緩存任何序列化的PHP結構。PHP船舶,所以我建議在看APC對象緩存。
http://uk1.php.net/manual/en/ref.apc.php
一定要對清理一些邏輯目錄結構發生變化時的緩存。
查看更新後的代碼,一個簡單的文件系統的版本... – Baba