Tuesday, February 16, 2010

Use Cache_Lite without Pear

This post explains how to use Cache_Lite without using Pear.

Sometimes it may be impractical to install Pear packages on the server -- perhaps Pear isn't installed, perhaps you lack administrative rights, etc. Regardless, the steps below should assist you in using Cache_Lite under these circumstances.

  1. Download the 'manual installation' version of Cache_Lite.
  2. Extract this to some location on your local disk. Open a shell and navigate to this location; next we're going to adjust up the extracted files to better mimic the Pear installation.
  3. Rename the top-level directory from Cache_Lite-X.Y.Z to Cache.
  4. Optional -- you are free to remove the docs and test sub-directories if you wish; this will save on disk space.
  5. Now take the Cache directory and all its contents and place them in someplace accessible from your php include path; in my case I chose the quick and dirty approach and put it in $_SERVER['DOCUMENT_ROOT']/include:
  6. [user@localhost:/var/www/web/include/Cache]$ ls -A1
    LICENSE
    Lite
    Lite.php
    TODO

  7. Incorporate Cache_Lite into your PHP pages as described in the documentation, but with the changes listed below. These will insure that Cache_Lite functions adequately in the absence of Pear.

  8. require_once( 'include/Cache/Lite.php' );

    $cache_lifetime = 30; // in seconds
    $cache_id = '1234';
    $cache_options = array( 'cacheDir' => '/tmp/',
    'lifeTime' => $cache_lifetime,
    'pearErrorMode' => CACHE_LITE_ERROR_DIE
    );

    $Cache_Lite = new Cache_Lite( $cache_options );

    if( $data = $Cache_Lite->get( $cache_id ) )
    {
    // data is the JSON connection string
    $returnValue = $data;
    }
    else
    {
    // value is an array of database values (not shown)

    $data = json_encode( $value );

    // cache the JSON-encoded connection string
    $Cache_Lite->save( $data, $cache_id );

    $returnValue = $data;

    }

  9. Notice that we've set the options for Cache_Lite to not use Pear error mode; this line is important as it will otherwise attempt to use the Pear error handler, which can result in a failure to load since it will attempt to include PEAR.php.
  10. Also note the use of the caching mechanism; here we're caching a JSON string created from database entries. Successive loads of this page first check the cache validity, and if valid, returns the existing cached JSON string. If the cache is out of date, the system will then query the database, create the JSON string, then cache it before returning it back to the caller.

1 comment:

php web developer said...

Appreciate the work you did here as I want to use Cache_Lite but not PEAR.