PHP DevCenter
oreilly.comSafari Books Online.Conferences.


Caching PHP Programs with PEAR
Pages: 1, 2

Output caching

Looking back at the introductory example of a commerce application, you're now able to cache parsed template elements, or catalog information you used to pull from the database on each request.

We now go a step further and cache a script's complete output with the Cache_Output class.

Example 2: Caching a script's output

// Load PEAR Cache's Output Cache

require_once 'Cache/Output.php';

$cache = new Cache_Output('file', array('cache_dir' => '.') );

// Compute unique cache identifier for the page we're about
// to cache. We'll assume that the page's output depends on
// the URL, HTTP GET and POST variables and cookies.

$cache_id = $cache->generateID(array('url' => $REQUEST_URI, 'post' => $HTTP_POST_VARS, 'cookies' => $HTTP_COOKIE_VARS) );

// Query the cache

if ($content = $cache->start($cache_id)) {
// Cache Hit

echo $content;

// Cache Miss

// -- content producing code here --

// Store page into cache

echo $cache->end();

With the Cache_Output class, it is easily possible to turn a dynamic, database-driven web application into a static one. This can drastically improve a site's performance.

Related Reading

PHP Pocket ReferencePHP Pocket Reference
By Rasmus Lerdorf
Table of Contents
Sample Section
Full Description
Read Online -- Safari

More and more web sites are using GZIP compression for their HTML content. This reduces the server's bandwidth, and thus the costs for the generated traffic. Furthermore, it increases the user experience for those using modem connections. Cache_OutputCompression extends the functionality of the Cache_Output class, as it caches the GZIP compressed version of the generated HTML to save the CPU time needed to compress the content.

Customized solutions

In this last section, I explain how the PEAR Cache framework can be used to develop customized caching solutions. As an example, I have chosen a class called MySQL_Query_Cache that caches the result sets of SELECT queries.

Let's start with the class's variables -- constructor and destructor. The constructor is used, as before with the Cache_Function and Cache_Output classes, to transport the cache container options. The destructor closes the MySQL connection and runs the cache's garbage collection, if needed.

require_once 'Cache.php';

class MySQL_Query_Cache extends Cache {
  var $connection = null;
  var $expires    = 3600;

  var $cursor = 0;
  var $result = array();

  function MySQL_Query_Cache($container  = 'file', 
      $container_options = array('cache_dir'=> '.', 
      'filename_prefix' => 'cache_'), $expires = 3600)
    $this->Cache($container, $container_options);
    $this->expires = $expires;      

  function _MySQL_Query_Cache() {
      if (is_resource($this->connection)) {


Before we come to the juicy part, where we actually perform and cache the query, we need some more helper functions.

function connect($hostname, $username, $password, $database) {
  $this->connection = mysql_connect($hostname, $username, $password) or trigger_error('Could not connect to database.', E_USER_ERROR);

  mysql_select_db($database, $this->connection) or trigger_error('Could not select database.', E_USER_ERROR);

function fetch_row() {
  if ($this->cursor < sizeof($this->result)) {
    return $this->result[$this->cursor++];
  } else {
    return false;

function num_rows() {
  return sizeof($this->result);

We already have ready the functionality needed to connect to a MySQL database, to fetch a row from a cached result set, and to get the number of rows in the current set. Let's see how we perform -- and cache -- a database query:

function query($query) {
  if (stristr($query, 'SELECT')) {
    // Compute unique cache identifier for this query

    $cache_id = md5($query);

    // Query the cache

    $this->result = $this->get($cache_id, 'mysql_query_cache');

    if ($this->result == NULL) {
      // Cache Miss

      $this->cursor = 0;
      $this->result = array();

      if (is_resource($this->connection)) {
        // Use mysql_unbuffered_query(), if available

        if (function_exists('mysql_unbuffered_query')) {$result = mysql_unbuffered_query($query, $this->connection);
        } else {$result = mysql_query($query, $this->connection);

        // Fetch all result rows

        while ($row = mysql_fetch_assoc($result)) {$this->result[] = $row;

        // Free MySQL Result Resource


        // Store result set in cache

        $this->save($cache_id, $this->result, $this->expires, 'mysql_query_cache');
  } else {
    // No SELECT query, don't cache it

    return mysql_query($query, $this->connection);

Example 3: The MySQL query cache in action

require_once 'MySQL_Query_Cache.php';

$cache = new MySQL_Query_Cache();
$cache->connect('hostname', 'username', 'password', 'database');
$cache->query('select * from table');

while ($row = $cache->fetch_row()) {
  echo '<p>';
  echo '</p>';

With this information, you should be able to get started caching PHP web pages for most common applications.

Sebastian Bergmann is the author of a variety of PHP software projects such as PHPUnit and phpOpenTracker.

Return to the PHP DevCenter.

Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!

Sponsored by: