Improving Performance of Remote Requests By Caching The Result

Improving Performance of Remote Requests By Caching The Result Posted May 30, 2009 @ 7:22pm by Phil

I recently created a script to retrieve status updates from Twitter but actually using that script as is would be impractical for most sites due to the limit of 60 requests per minute. What we need to do is augment that script with some sort of caching mechanism. It just so happens I have created said caching mechanism (below). I have tried to make this script as general as possible so that it can be used with anything that needs caching. I plan on using it to cache my Twitter updates and RSS feeds.

<?php
  function cache_result ($file, $expires, $expression)
  {
    if (file_exists($file))
    {
      $lines = file($file);
      if (rtrim($lines[0], "\r\n") + $expires > time())
      {
        return unserialize(rtrim($lines[1], "\r\n"));
      }
    }
    
    $result = eval($expression);
    
    $handle = fopen($file, "w");
    fwrite($handle, time()."\n".serialize($result)."\n");
    fclose($handle);
    
    return $result;
  }
?>

Download Source: cache_result.php

The challenge of creating this script was passing in an expression that would only be executed if the cached copy had expired and keeping it general purpose. My first thought was to use the command design pattern and provide a class that could be overridden and passed in to provide that functionality. But I like my PHP to remain lean and mean, so I chose a more PHP approach and to allow the user to pass in an expression and use the eval function to execute it if the cached version has expired.

Here is an example of using this function:

<?php
  cache_result("twitter_updates", 600, "return twitter_updates('username', 'password');");
?>

Download Source: example.php

The first argument is the name of the file that the cached result will be saved as. The second argument is the time the result will remain cached before re-evaluating the expression. The final argument is the expression to be evaluated and cached.

Tags: PHP/MySQL, Webmasters Tips