Caching results in a PHP function

If you have a function that will get called lots of times, and you'd like to cache the results so as not to incur a performance penalty for hitting the disk/DB again use static variables.

function get_user($id) {
  // Sanitize the input
  $id = intval($id);

  // Declaring as static prevents the variable from dying when the function exits
  static $cache;

  // If the data is already in the cache just return that
  if ($cache[$id]) { return $cache[$id]; }

  // Get the data from the DB/Disk/Slow Source
  $rs = mysql_query("SELECT * FROM UserTable WHERE ID = $id");
  $ret = mysql_fetch_assoc($rs);

  // Store the results in the cache so it will be there next time
  $cache[$id] = $ret;

  return $ret;
}

This will store the results in cache (memory), speeding up subsequent requests. This cache will last until your script ends. To store across multiple script executions you'll want to look at something like memcache.

Leave A Reply - 1 Reply
Replies
Ben 2010-01-24 10:21pm - No Email - Logged IP: 76.22.110.84

This technique is called memoization.

All content licensed under the Creative Commons License