2011-12-26 103 views
0

我正在使用codeigniter (MVC)extjs爲應用程序。 該應用程序包含許多帶用戶相關數據的extjs網格。我想緩存服務器json響應到特定時間。json數據緩存爲extjs網格

我有一個想法,以實現這個如下

if(cache file exists and not expired) 
{ 
    $data = read_file(cache file path);// the cache file contains json encoded data with .json extention 
} 
else 
{ 
    $result = call to a model function; // returns data from a mysql query 
    $data = json_encode($result); 
    //creating cache file with retrived data 
    wite_file(cache file path, $data) 
} 
echo $data; // $data is in json format 

我想實現緩存這種方式。這是正確的方式嗎? 完全我想實現一個自定義的json緩存庫緩存服務器json數據extjs網格

是否有任何json緩存庫已經可用於codeigniter。 請幫助你的建議

回答

0

笨具有幾乎完全相同你的描述構建了什麼,他們稱其爲高速緩存驅動程序:http://codeigniter.com/user_guide/libraries/caching.html

在你的情況,你會想要啓動它是這樣的:

$this->load->driver('cache', array('adapter' => 'file', 'backup' => 'file')); 

if (! $foo = $this->cache->get('foo')) 
{ 
    echo 'Saving to the cache!<br />'; 
    $foo = 'foobarbaz!'; 

    // Save into the cache for 5 minutes 
    $this->cache->save('foo', $foo, 300); 
} 

echo json_encode($foo); 

它會寫將緩存數據存檔。

在你的情況下,缺點是CI序列化緩存文件中的數據,而不是使用JSON。我想你可以使用json_encode()而不是serialize()來覆蓋驅動程序。上面的方法會浪費一點資源,因爲它在序列化和輸出上使用json編碼。

+0

謝謝phirschybar。我查看codeigniter緩存庫,它使用serialize將響應數據寫入緩存文件並反序列化以從緩存文件讀取數據。我嘗試用json_encode替換序列化,但它給出錯誤[json](php_json_encode)類型不受支持,編碼爲null。我認爲json_encode()不能編碼mysql結果對象。我st-rucked here.Any建議嗎? – nani1216 2011-12-29 11:36:59

+0

你運行的是哪個版本的php? – phirschybar 2011-12-29 15:46:56

+0

我正在運行PHP 5.3.1 – nani1216 2011-12-30 05:43:39

0

是的,它聽起來是一個好方法,要知道文件是否過期,你可以使用文件系統上的創建時間戳。

stat函數應該爲您提供關於文件的足夠信息,以便在需要時過期。

Codeigniter似乎有一些caching mechanism遺憾的是,它似乎只適用於網頁,如果您使用視圖來渲染你的JSON,你可以使用它。

+0

感謝您的快速回復RageZ。我想定製philsturgeon緩存庫而不是實現我自己的。 – nani1216 2011-12-29 11:41:42