Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4995669
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类:

2010-06-13 09:43:23

Some web sites and applications have complex ways of parsing and manipulating data before the information is presented to the visitor or user. This article addresses the need for page caching, a way of processing the information once and caching the page's content for any subsequent views. I'm writing this article in view of providing page caching for simple CMSs (Content Management Systems). The key points for processing page caching are as follows:

  1. If there is already a cache file, present it. Else...
  2. Start PHP's output buffer
  3. Process your business logic and present the XHTML
  4. Store the buffer as a cache file
  5. Output the contents of the buffer to the screen

So, with all of that said and done let's look at the code to perform this functionality:

 

// The name and path for the cache file
$cache_file_directory = "/home/username/public_html/cache/";
$cache_filename = $cache_file_directory . __FILE__ . ".cache";

// If the cache file exists, present it
if(file_exists($cache_filename))
{
    $file_handle = fopen($cache_filename, "r");
    echo fread($file_handle, filesize($cache_filename));
    fclose($file_handle);
}
else
{
    // Create a temporary swap file
    $swap_filename = $cache_file_directory . md5(getmypid());
    $swap_handle = fopen($swap_filename, "w");
    
    // Start the output buffer from here
    ob_start();
    
    /*** Process and render your web page here ***/

    // Write the contents of the output buffer to the swap file
    fwrite($swap_handle, ob_get_contents());
    fclose($swap_handle);

    // Rename the swap file to the final cache file name
    rename($swap_filename, $cache_filename);

    // Stop the output buffer and clear its contents
    ob_end_flush();
}


As you can see by the above code, the functionality to perform page caching is quite simplistic, although there are a few points to consider:

  • Make sure that the cache file directory is writable (chmod 777 in most cases)
  • To clear the cache all you have to do is delete the .cache files
  • If you update any information on your page then you must clear the cache
  • If the page is updated by your users or visitors then you must disable caching

One important point I would like to cover is to do with the way we use swap files to stop file write conflictions. This is necessary so that two simultaneous fopens do not cause the cache file to erroneously written if two visitors try to create a cache file at the same time

阅读(1404) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~