2012-11-29 32 views
0

反正緩存readdir()的結果嗎?現在我每次進入網站上的特定網頁時,都會在目錄樹上執行readdir()。緩存readdir()

UPDATE:

  • 的目錄結構對於所有用戶都是相同的。
  • 不幸的是我的共享主機不支持APC或內存緩存:-(
+0

查看更新後的代碼,一個簡單的文件系統的版本... – Baba

回答

1

您可以使用Memcachefilemtime

$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); 
    } 
} 
+0

真棒工作,謝謝! – Cudos

+0

不客氣 – Baba

0

,如果你啓動一個會話你可以將其存儲在一個會話變量,看看session_start()函數等

+0

這將存儲相同的數據在網站上每一個用戶,並且可能會不必要地涉及啓動會議。 dir結構可以在整個應用程序範圍內緩存,除非由於某些原因,在問題中沒有提及目錄是特定於用戶的。 – Tim

+0

當然。不清楚他的要求是什麼... – ScoPi

0

您可以使用多種方法與APC這幾天緩存任何序列化的PHP結構。PHP船舶,所以我建議在看APC對象緩存。

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

一定要對清理一些邏輯目錄結構發生變化時的緩存。