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:
- If there is already a cache file, present it. Else...
- Start PHP's output buffer
- Process your business logic and present the XHTML
- Store the buffer as a cache file
- 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
阅读(1449) | 评论(0) | 转发(0) |