Posted By

MMDeveloper on 12/29/09


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

BrianCoyDesign
Priestd09


Website Cache (query results, etc) to file for quicker response time


 / Published in: PHP
 

URL: http://skyward.nefec.org

This was a simple home-grown caching system for queries but it can really be used to store anything in cache. This will reduce server load on common queries, etc. In the code below, you will notice references to the following classes/properties, they are explained below what they hold (this class is integrated into a much larger entity).

$controller_config->cacheDir = This is the writeable directory path where the cache files are stored.

$controller_config->useCache = This is a boolean true/false as to whether the site uses cache or not. This is helpful during new development or troubleshooting.

$controller_config->cacheLifetime = This is the lifespan of the cache file (in seconds)

The way I use this is that I have to generate a unique "file id" that uniquely identifies the request. This is usually the classnamemethodName plus a hash of all the supplied arguments. For this example I'll keep it simple and show how I integrated the cache system with the event calendar.

The method that generates the month hash for the event calendar (entire month, days, events, etc) is named "viewCalendar_month" and accepts the arguments $month and $year; therefor:

$cache = new cache();
$fileID = "eventCal_monthHash_" . $month . "-" . $year;

if ($cache->hasCache($fileID) === true) {
    $hash = $cache->getCache($fileID, true);
}
else {
    $hash = $this->generateCalendarHash($month, $year, true);
    $cache->writeCache($fileID, $hash, true);
}

It checks for a valid cache file with the supplied "file id". If it exists, it just grabs the contents of that file, if a valid cache file does not exist, it just re-generates the data as if the cache system never existed and then creates a new (or updated) cache file for next time.

The getCache and writeCache methods have a boolean argument of $serialized. This tells the cache system if the data needs to be serialized or unserialized before writing/reading the data (respectively). This is handy for storing arrays or objects to cache. An example where you would not need the data serialized is if you were storing a pre-JSON encoded result.

On a side note, I have my personal system set to let the cache files be valid for 24 hours (data doesn't change often). I do have a separate cleanup job that runs once a week and cleans out any .txt files in the cache directory that are older than 24 hours.

  1. <?php
  2.  
  3. /**
  4.  * This is the cache management class
  5.  * @package Skyward_Landing_Page
  6.  * @subpackage Cache
  7.  * @filesource
  8.  * @author Matt Ford
  9.  * @version 1.0
  10.  */
  11.  
  12. //if (!defined("parentFile")) {die("Direct Access Not Allowed");} else {}
  13.  
  14. class cache {
  15.  
  16. /**
  17. * This method determines if the supplied file id has a valid cached version or not
  18. * @access public
  19. * @author Matt Ford
  20. * @param string $fileID the ID of the cache file
  21. * @return boolean true false result
  22. */
  23. public function hasCache($fileID) {
  24. global $controller_config;
  25.  
  26. $file = $controller_config->cacheDir . $fileID . ".txt";
  27.  
  28. if (file_exists($file) && $controller_config->useCache === true) {
  29. $mtime = filemtime($file);
  30. $ctime = mktime();
  31. $diff = ($ctime - $mtime);
  32.  
  33. if ($diff >= $controller_config->cacheLifetime) {
  34. //syslog(LOG_INFO, "Cache for this data ($fileID) is expired");
  35. @unlink($file);
  36. return false;
  37. }
  38. else {
  39. //syslog(LOG_INFO, "This data ($fileID) is cached");
  40. return true;
  41. }
  42. }
  43. else {
  44. //syslog(LOG_INFO, "Cache does not contain this data ($fileID)");
  45. return false;
  46. }
  47. }
  48.  
  49. /**
  50. * This method deletes any existing cache file for the supplied fileID and writes a new cache file
  51. * @access public
  52. * @author Matt Ford
  53. * @param string $fileID the ID of the cache file
  54. * @param mixed $data string, array, object, whatever the data is
  55. * @param boolean $serialized whether or not to serialize the data before writing to cache file
  56. */
  57. public function writeCache($fileID, $data, $serialized = false) {
  58. global $controller_config;
  59.  
  60. if ($controller_config->useCache === true) {
  61. $file = $controller_config->cacheDir . $fileID . ".txt";
  62. @unlink($file);
  63.  
  64. $data = ($serialized === true) ? serialize($data) : $data;
  65. //syslog(LOG_INFO, "Writing cache file $fileID");
  66. @file_put_contents($file, $data);
  67. } else {}
  68. }
  69.  
  70. /**
  71. * This method retrieves the data from the cache file
  72. * @access public
  73. * @author Matt Ford
  74. * @param string $fileID the ID of the cache file
  75. * @param boolean $serialized whether or not to unserialize the data before before returning it
  76. * @return mixed string, array, object, whatever the data is
  77. */
  78. public function getCache($fileID, $serialized = false) {
  79. global $controller_config;
  80.  
  81. $file = $controller_config->cacheDir . $fileID . ".txt";
  82.  
  83. if (file_exists($file) && $controller_config->useCache === true) {
  84. $data = file_get_contents($file);
  85. $data = ($serialized === true) ? unserialize($data) : $data;
  86. //syslog(LOG_INFO, "Cache utilized and retrieved for $fileID");
  87. return $data;
  88. }
  89. else {
  90. //syslog(LOG_INFO, "Cache does not contain this data ($fileID)");
  91. return "";
  92. }
  93. }
  94. }
  95. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: DenisBeurive on April 28, 2010

Hello,

You can also use the Zend Framework : http://framework.zend.com/manual/fr/zend.cache.html

A+

You need to login to post a comment.