我有一个PHP页面缓存脚本;如何使它在生成新页面之前显示以前缓存的页面


I have a PHP page caching script; how do I make it display the previously cached page before generating a new one?

以下是我正在使用的代码:

<?php
    $interval = 5 * 60;
    $filename = "cache/".basename( rtrim( $_SERVER["REQUEST_URI"], '/' ) ).".cache";
    if ( file_exists( $filename ) && (time() - $interval) < filemtime( $filename ) ) {
        readfile( $filename );
        exit(); 
    }
    ob_start(); 

    include 'dynamicpage.php'; 
?>

<?php
    // More page generation code goes here
    $buff = ob_get_contents(); // Retrive the content from the buffer
    // Write the content of the buffer to the cache file
    $file = fopen( $filename, "w" );
    fwrite( $file, $buff );
    fclose( $file );
    ob_end_flush(); // Display the generated page.
?>

目前,如果缓存的页面超过5分钟,此脚本将生成一个新的缓存文件来替换旧的缓存文件。有没有什么方法可以先显示旧的缓存,然后在后台生成新的缓存页面?我的主机很弱,所以要等页面加载完成需要很长时间。

我会设置一个crontab来每5分钟处理一次页面,并始终为用户提供缓存的页面。

如果你不能设置crontab,你可以输出一个隐藏的iframe,里面有动态页面加载,这样页面加载很快,但另一个实例正在后台加载(不是一个很好的解决方案,但很有效)。

听起来您需要一个异步PHP请求。从本质上讲,这会触发另一个脚本与当前脚本一起运行@John的想法是正确的,但是crontab只是异步运行缓存过程的一种方式。他的解决方案的缺点是,无论是否需要,它都会每5分钟运行一次。

有许多库和其他一些小程序可以帮助您设置异步PHP处理,但正如@John所说,它也有一些涉及。

这里有一些资源可以帮助做到这一点:

  • php并行处理(php库)
  • Gearman(原生PHP库)
  • 异步PHP调用?(SO问题)

Smarty模板引擎是一个简单而小型的工具,它有很多内置的缓存功能,没有框架规则。http://www.smarty.net/