2010-08-19 36 views
1

我正在嘗試創建一個小模板系統,並且有一個函數可以遍歷一系列項目。 目前我使用的輸出緩衝功能,幷包括所以我可以加載模板文件,而它有範圍的類。php,模擬include?緩存系統

function loadTemplate($name, $vars) { 
    $buf = ''; 
    $path = $name . '.html'; 
    if (file_exists($path)) { 
     $this->vars = $vars; 
     ob_start(); 
     include($path); 
     $buf = ob_get_clean(); 
    } 
    return $buf; 
} 

我只是想知道如果我可以在初始模板存儲在數組中,然後讓它運行(好像它被列入),同時保持範圍,等等。

function loadTemplate($name, $vars) { 
    $buf = $template = ''; 
    if (isset($this->cache[$name])) 
     $template = $this->cache[$name]; 
    else { 
     $path = $name . '.html'; 
     $template = file_get_contents($path); 
     $this->cache[$name] = $template; 
    } 
    //Exec template here with scope. 
} 

還是我只是被迂腐,並試圖微優化:)

+0

模板系統在PHP多餘的。 PHP本身就是一個模板引擎,你爲什麼要爲它增加更多的開銷? – NullUserException 2010-08-19 13:42:34

+0

可能是因爲PHP是一個相當複雜的模板語言,通常PHP模板代碼看起來比較乾淨的模板系統更可怕。在我工作的公司中,很多webdesigners根本無法用PHP處理非常好的工作。如果像這樣使用'

+0

我只是試圖從代碼中分離內容,因此可以在不影響用戶定製的情況下應用更新。 – Alex 2010-08-19 14:05:14

回答

0

任何緩存杉杉將尋找到的CakePHP按NullUserException的評論:)

0

我不認爲它使太大的區別,如果你包括模板再次,就像你說的自己......它將是微型優化。 但是,您可以做的是將已包含的模板源保存到數組中,並使用模板名稱作爲數組的關鍵字。 運行loadTemplate函數時,只需執行array_key_exists以查看它是否已包含。但如果可以,我會推薦smarty template engine。我在我的項目中使用它,發現它很完美。我已經適應了一些,使我的代碼更流暢,但現在對我來說確實非常完美。

0

只是繼續包括它。唯一的選擇是閱讀內容然後評估它們,那會更糟。由於頁面已經解析爲操作碼,所以第二個包含的開銷應該明顯更少...

+0

「頁面已被解析爲字節碼」什麼? – NullUserException 2010-08-19 13:41:23

+0

對不起,我的意思是說操作碼... – ircmaxell 2010-08-19 14:00:30

1

如果我是你並且在模板文件中有複雜的操作,我會將它們保存到文件系統中。我已經修改了你的功能,我想你會明白髮生了什麼:

<?php 

function template($name, $vars = array()) 
{ 
    $cache = 'cache/'; // Path to cache folder, must be writeable 
    $expire = 3600 * 3; // Cache lifetime, 3 hours 
    $path = $name . '.html'; 
    $cache_file = $cache . sha1($path) . '.txt'; // Generate cache file path and hash-name 

    // If cache file exists and it hasn't expired yet we must get cached data 
    if (file_exists($cache_file) && filemtime($cache_file) > (time() - $expire)) 
    { 
     return unserialize(file_get_contents($cache_file)); 
    } 

    // Return NULL if template file doesn't exist 
    if (!file_exists($path)) 
    { 
     return null; 
    } 

    $this->vars = $vars; 

    ob_start(); 
    include_once $path; 
    $output = ob_get_clean(); 

    // Save output to the cache file 
    file_put_contents($cache_file, serialize($output)); 

    return $output; 
} 

?> 

P.S.沒有測試過這個功能。

+0

我的主要想法是嘗試減少磁盤讀取的數量,但我認爲這隻會使性能提升略微複雜化。 – Alex 2010-08-19 14:09:35

+0

我不確定這會做什麼必要的事情......問題是(從我收集的內容來看)文件的輸出將根據'$ vars'而改變。所以你至少需要將你的緩存文件定義調整爲依賴於該數組。如果有任何暫時的變化(或者至少會導致每個「模板」文件的大量緩存文件),那麼這可能會導致緩存命中率降低...... – ircmaxell 2010-08-19 14:46:33

0

這是你可以實現的最無用的緩存。 你最好想一下HTTP條件獲取實現,它根本不需要調用temlpate。然後去操作碼緩存,它會自動緩存你的包含。

但在你來分析你的應用程序/ templater看到,如果你需要在所有