In a mod_perl environment, your variables (like database handles) can live longer than a single request if you declare them in a scope "outside" of the request.
For example:
package MyHandler;
use strict;
use warnings 'all';
use Apache2::RequestRec;
use Apache2::RequestUtil;
# Declare it here:
my $persistent_thing;
sub handler : method {
my ($class, $r) = @_;
# The first time this is executed in a child process, it will be cre
+ated.
# After that, you will just reuse the same one:
$persistent_thing ||= make_the_thing();
}
1;
Please also check out Ima::DBI::Contextual as it solves the whole thing.
package MyDBI;
use base 'Ima::DBI::Contextual';
my @dsn = ( 'DBI:mysql:dbname:hostname', 'username', 'password', {
# Other options go here:
RaiseError => 1,
});
__PACKAGE__->set_db('Main', @dsn);
1;
Then, elsewhere:
use MyDBI;
# Automatically pooled and recreated if the old one times out or dies:
my $dbh = MyDBI->db_Main;