On Tue, Mar 27, 2001 at 09:50:33PM +0100, Matt wrote:

> I want to cache some values in my handlers so they don't keep having
> to look stuff up, and so I figured a Cache::SharedMemoryCache would
> be the way to go.

It all depends on what you want to cache and why.  If you wanted to
save a trip to the database on each request, a really simple mod_perl
handler could look something like this:

  package MyApplication;

  use strict;
  use Apache::Request;
  use Cache::SharedMemoryCache;

  sub handler
  {
    my ( $request );

    my $cache = new Cache::SharedMemoryCache( );

    my $data = $cache->get( 'data' );

    if ( not defined $data )
    {
      $data = expensive_database_request( );

      $cache->set( 'data', $data );
    }

    $request->content_type( 'text/plain' );
    $request->send_http_header( );
    $request->print( "data: $data" );
  }
  

The first time this handler is run, the data will not be found in the
cache.  The second time, however, the data will be returned from the
cache, saving a trip to the database.

The other question is whether or not to share the cache instance
itself globally.  Technically, this is up to you.  Personally I
wouldn't bother, considering the overhead of instantiating the cache
is so low that I would rather keep it local to the handler (as I did
above).  I tend to only share data globally in mod_perl handlers very
judiciously, and even then I wrap the data in an object that provides
accessor methods.  For an example of an object that wraps shared data,
check out Cache::MemoryCache, which simply caches data inside the
process.

Hope this helps a bit.  Cheers,

-DeWitt


Reply via email to