2012-04-01 74 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