Apache::Session::Lazy - Perl extension for opening Apache::Sessions on first read/write access.


See Apache::Session


The Module

Apache::Session is a persistence framework which is particularly useful for tracking session data between httpd requests. Apache::Session is designed to work with Apache and mod_perl, but it should work under CGI and other web servers, and it also works outside of a web server altogether.

Apache::Session::Lazy extends Apache::Session by opening Sessions only after they are either modified or examined (first read or write access to the tied hash.) It should provide transparent access to the session hash at all times.

Uses Of Apache::Session::Lazy

Apache::Session::Lazy was designed to allow Apache::Session to achieve prevent unnecessary work in accessing the data store, if a session is not going to be touched, and allow for session locking to exist for the least possible amount of time, so that other access to the same session is possible.


The interface for Apache::Session::Lazy is only different for tieing the Session. You must an additional parameter after tie %session. So the new tie will look like-

Get a new session using DBI:

 tie %session, 'Apache::Session::Lazy', 'Apache::Session::MySQL', undef,
    { DataSource => 'dbi:mysql:sessions' };

Restore an old session from the database:

 tie %session, 'Apache::Session::Lazy', 'Apache::Session::MySQL', $session_id,
    { DataSource => 'dbi:mysql:sessions' };

Check for a session:

 eval {  
   tie %session, 'Apache::Session::Lazy', 'Apache::Session::MySQL', $session_id,
      { DataSource => 'dbi:mysql:sessions' };


You can now subclass Apache::Session::Lazy. This allows you to force users to use only one of the Apache::Session interfaces by use()-ing that module, and overiding the checks subroutine:

 package My::Apache::Session::Lazy;
 use Apache::Session::Flex;
 use Apache::Session::Lazy;
 @My::Apache::Session::Lazy::ISA = Apache::Session::Lazy;

 sub checks { # This holds the parameters to be passed to Apache::Session.
   unless ( $_[0] =~ m/Apache::Session::Flex/i ) {
     die ('Please just flex it.');
   } elsif ( $_[2]->{'Generate'} ne 'ModUniqueId' ) {
     die ('Use UniqueId, it is the j33test.');
   } else {
     return 1;

   return; # Just in case they're catching dies.


Gyan Kapur <>

With help from merlyn.