PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

Caching PHP Programs with PEAR

by Sebastian Bergmann
10/11/2001

Contents:

  • Caching in context
  • Where to get PEAR Cache
  • How PEAR Cache works
  • Function call caching
  • Output caching
  • Customized solutions

Caching in context

Caching is currently a hot topic in the PHP world. Because PHP produces dynamic web pages, scripts must be run and results must be calculated each time a web page is requested, regardless if the results are the same each time. In addition, PHP compiles the script every time it is requested. This overhead can seriously slow down a site with heavy traffic. Fortunately, the results of a web request can be stored, or cached, and presented to matching requests without having to re-run or recompile the scripts. Commercial products like ZendCache or open-source solutions such as Alternate PHP Cache provide a means to cache the compiled version of a PHP script -- the byte-code.

While these "PHP land" solutions scratch an itch in PHP's design, "Userland" solutions can go a step further and address general bottlenecks in Web application design and programming. (The term PHP Land refers to the language level of PHP, for instance, the Zend Engine, that drives PHP 4. The term userland refers to something that is written by users of PHP.)

Imagine a commerce application with a large catalog stored in a database. It is realistic to assume that the catalog information will change only at specific times, such as once or twice a day. Still, for every request to the product's page, a database query is performed. This overhead could be easily avoided by caching either the query's result or the complete HTML output of the requested page.

PEAR's Cache package offers a framework for the caching of dynamic content, database queries, and PHP function calls.

Where to get PEAR Cache

Perl has CPAN, and TeX has CTAN. But PHP also has a central repository for classes, libraries, and modules. It's called PEAR, which stands for PHP Extension and Add-On Repository. You can read all about PEAR in OnLAMP.com's recent articles An Introduction to PEAR and A Detailed Look at PEAR.

For this article, I'll assume that you already have a PEAR environment set up. The examples in this article have been developed and tested with a development version of PEAR Cache, available either via CVS or as a snapshot here.

How PEAR Cache works

The PEAR Cache package consists of a generic Cache class and several specialized subclasses -- for example, a class to cache function calls or a script's output. The Cache class can use a variety of so-called Container classes that actually store and manage the cached data.

Following is a list of PEAR Cache's current container implementations along with their respective parameters

  • file -- The file container stores the cached data in the file system. This is the fastest container.

  • cache_dir -- This is the directory where the container stores its files.

  • filename_prefix -- The file name prefix for the cache files, for instance "cache_".

  • shm -- The shm container stores the cached data in the shared memory. Benchmarks indicate that the current implementation of this container is much slower than the file container.

  • shm_key -- The shared memory key to be used.

  • shm_perm -- Permissions for the shared memory segment.

  • shm_size -- The size of shared memory to be allocated.

  • sem_key -- The semaphore key to be used.

  • sem_perm -- Permissions for the semaphore.

  • db -- PEAR's database abstraction layer.

  • dsn -- DSN of the database connection to be used. Please refer to the PEAR DB documentation for details.

  • cache_table -- Name of the table to be used.

  • phplib -- The phplib container uses the a database abstraction layer to store its cached data.

  • db_class

  • db_file

  • db_path

  • local_file

  • local_path

  • ext/dbx -- PHP's database abstraction layer extension. This is currently the container of choice if you want to store the cached data in a database.

  • module

  • host

  • db

  • username

  • password

  • cache_table

  • persistent

The performance gain from the use of PEAR Cache greatly depends on your choice for the cache container to be used. For instance, it makes obviously no sense to store the result of a database query again into a database.

Function call caching

PEAR Cache's Function Cache module caches the output and result of any function or method, no matter if they are built-in PHP functions or user-defined ones. By default, it uses the File container and puts the cache data into a directory named function_cache.

The Cache_Function class's constructor accepts up to three parameters, all three being optional:

  • $container

    Name of the cache container to use.

  • $container_options

    Array of parameters for the cache container.

  • $expires

    Number of seconds after which a cache object expires.

A cached function call is triggered by wrapping the normal function call using the Cache_Function class's call() method. Using call() is quite easy. Its first parameter gives the name of the function (or method) to call, followed by the parameters of the function (or method) to be called. The second parameter of call() is the first one of the function (or method) to be called, and so on. Let's have a look at an example:

Example 1: Caching function and method calls

<.;?php
// Load PEAR Cache's Function Cache

< 'Cache/Function.php';

// Define some classes and functions / methods
// for demonstration

class foo {
  function bar($test) {
    echo "foo::bar($test)<br>";
  }
}

class bar {
  function foobar($object) {
    echo '$'.$object.'->foobar('.$object.')<br>';
  }
}

$bar = new bar;

function foobar() {
  echo 'foobar()';
}

// Get Cache_Function object

$cache = new Cache_Function();

// Cached call to static method bar() of class foo
// (foo::bar())

$cache->call('foo::bar', 'test');

// Cached call to method foobar() of object bar
// ($bar->foobar())

$cache->call('bar->foobar', 'bar');

// Cached call to function foobar()

$cache->call('foobar');
?>

Caching of function calls comes in handy in a variety of situations such as time-consuming XSL transformations of XML sources that only change on a daily basis.

Pages: 1, 2

Next Pagearrow




Tagged Articles

Post to del.icio.us

This article has been tagged:

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

cache

Articles that share the tag cache:

An AJAX Caching Strategy (13 tags)

Caching PHP Programs with PEAR (7 tags)

Eleven Metrics to Monitor for a Happy and Healthy Squid (3 tags)

Peering Squid Caches (3 tags)

Caching Dynamic Content with JSP 2.0 (2 tags)

View All

pear

Articles that share the tag pear:

The Dynamic Duo of PEAR::DB and Smarty (37 tags)

Programming eBay Web Services with PHP 5 and Services_Ebay (12 tags)

Three-Tier Development with PHP 5 (6 tags)

PHP's PEAR on Mac OS X (6 tags)

Caching PHP Programs with PEAR (6 tags)

View All

programming

Articles that share the tag programming:

Rolling with Ruby on Rails (1374 tags)

Very Dynamic Web Interfaces (279 tags)

Ajax on Rails (231 tags)

Understanding MVC in PHP (202 tags)

A Simpler Ajax Path (186 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com