2012-04-01 69 views
2

我想部分緩存一些PHP文件。例如Php部分緩存

<? 
echo "<h1>",$anyPerdefinedVarible,"</h1>"; 
echo "time at linux is: "; 
// satrt not been catched section 
echo date(); 
//end of partial cach 
echo "<div>goodbye $footerVar</div>"; 
?> 

所以緩存頁面應該像爲 (cached.php)

<h1>This section is fixed today</h1> 
<? echo date(); ?> 
<div>goodbye please visit todays suggested website</div> 

,可能與模板做,但我直接想要它。因爲我想要替代解決方案。

+0

[你有什麼試過](http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – ghoti 2012-04-01 22:25:32

+0

生成這些行將比從緩存存儲中獲取2個密鑰更快。嘗試從數據庫緩存數據,不要浪費時間輸出,這是模板引擎的業務。 – 2012-04-01 22:26:12

+0

此代碼僅用於舉例。真正的代碼非常複雜,需要一些SQL查詢。我嘗試很清楚地表明我的問題。我想知道PHP緩存機制。 – Huseyin 2012-04-01 22:32:04

回答

3

看看php的ob_start(),它可以緩衝所有輸出並保存。 http://php.net/manual/en/function.ob-start.php

增加: 看http://www.php.net/manual/en/function.ob-start.php#106275您要:)功能 編輯: 這裏,甚至simpeler版本:http://www.php.net/manual/en/function.ob-start.php#88212 :)


這裏是一些簡單而有效的解決辦法:

template.php

<?php 
    echo '<p>Now is: <?php echo date("l, j F Y, H:i:s"); ?> and the weather is <strong><?php echo $weather; ?></strong></p>'; 
    echo "<p>Template is: " . date("l, j F Y, H:i:s") . "</p>"; 
    sleep(2); // wait for 2 seconds, as you can tell the difference then :-) 
?> 

actualpage.php

<?php  
    function get_include_contents($filename) { 
     if (is_file($filename)) { 
      ob_start(); 
      include $filename; 
      return ob_get_clean(); 
     } 
     return false; 
    } 

    // Variables 
    $weather = "fine"; 

    // Evaluate the template (do NOT use user input in the template, look at php manual why) 
    eval("?>" . get_include_contents("template.php")); 
?> 

您可以用http://php.net/manual/en/function.file-put-contents.php保存的template.php或actualpage.php的內容,一些文件,比如cached.php。然後你可以讓actualpage.php檢查cached.php的日期,如果太舊,讓它做一個新的,或者足夠年輕的時候只需要echo actualpage.php或者重新評估template.php而不重建模板。


後的意見,在這裏緩存模板:

<?php  
    function get_include_contents($filename) { 
     if (is_file($filename)) { 
      ob_start(); 
      include $filename; 
      return ob_get_clean(); 
     } 
     return false; 
    } 

    file_put_contents("cachedir/cache.php", get_include_contents("template.php")); 

?> 

要運行這個你可以直接運行緩存的文件,也可以包括這樣的一個其他的頁面上。像:

<?php 
    // Variables 
    $weather = "fine"; 

    include("cachedir/cache.php"); 
?> 
+0

它是有用的,但它可以緩存頁面的所有部分。我想要緩存php輸出的一些部分,而不是全部。 – Huseyin 2012-04-01 22:42:57

+0

你可以將它傳遞給一個函數,包含/需要它 - 它很靈活。當然,你可以將你自己的內容傳遞給一個緩存文件,然後查看fopen()和fwrite()函數 - 你仍然必須將內容傳遞給它們。您可以使用filemtime()來檢查文件的時間/日期,如果它變得過時,只需將其替換即可。 – ArendE 2012-04-01 22:56:35

+0

我想用它來創建靈活的模板。我需要包含在不同日期創建的多個部分的模板。因此,我需要任何忽略緩存中指定的php代碼段的函數。 – Huseyin 2012-04-01 23:00:07