kornerr has asked for the wisdom of the Perl Monks concerning the following question:

Hello. I need to keep custom object between HTTP requests. The user is supposed to provide information which helps initialize the object. I want the object to be alive between web page updates, because the object takes long to initialize. Thanks.
  • Comment on How to keep an object between HTTP requests?

Replies are listed 'Best First'.
Re: How to keep an object between HTTP requests?
by Corion (Patriarch) on Feb 15, 2010 at 08:50 UTC

    In general that's not possible. If you tell us more about your environment, we might be able to tell you how to cache the object. For example persistent environments like mod_perl, FCGI or HTTP::Server::Simple allow you to keep objects around.

    The most portable solution is to store (and restore) the object using Storable, but not all data types can be serialized that way.

    Another way would be to only load/initialize the parts of your object that you really need, instead of initializing everything just to display the log in screen. But you haven't told us about the nature of your object, so it's hard to advise on that.

      I use mod_perl under Apache2. Currently I'm examining Apache::Session module.

        It's easily possible to keep objects persistent per Apache process using mod_perl. If you need finer grained resolution, like for example per-user or per-session, then looking into one of the Session modules is worth it. Not every session module can handle large objects, as not all of them employ Storable to persist your large objects.

Re: How to keep an object between HTTP requests?
by bart (Canon) on Feb 16, 2010 at 16:08 UTC
    because the object takes long to initialize

    Why is that? Are you trying to hold something that is not possibly serialized, and better not shared across threads, like a database handle, or is it just a very complex data structure?

    If it's the former: don't do that. If it's a database handle, you might be able to make good use of a connection pool, see Apache::DBI.

    If it's the latter, you might be successful in trying to use Memcached to temporarily hold the serialized (with Storable) object in memory, instead of saving it to a file. There are some good modules to interface to it, like Cache::Memcached (Pure Perl) and Cache::Memcached::Fast (XS). Note that Memcached may trow data away if it's running short on memory, so be prepared to recreate the object, if necessary.