PHP DevCenter
oreilly.comSafari Books Online.Conferences.


Caching PHP Programs with PEAR

by Sebastian Bergmann


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'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

// 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()


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

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: