I had a solution for this (see below), but now realize it is flawed.
In a set of modules that manage persistent objects stored in a SQL database, what is a good way to manage the database connections? Goals would be: (1) have a single place in the code where all connections are made so that it is easy to change connection parameters later; (2) have connections be persistent (Apache::DBI); (3) have one point in each module at which the connection is made for that module; (4) in a given process, share all connections (i.e. connection is a singleton or is managed by a singleton); (5) Have modules that require database access manage their own connection rather than require that a database handle be passed to them; (6) Minimize change from current solution.
in a persistent environment (mod_perl) the class data ($dbh) gets initizalized only once, and potentially, the database connection referenced by $dbh can go away due to timeout or some other problem because the process can "live" for a long time. Apache::DBI is capable of checking for this, by "pinging" the database but it doesn't really get a chance to do this, because the connection is getting made only at BEGIN time, when the module is "use"-d.
Example of flawed code is below. MyProject::Dbh "isa" Apache::Singleton::Process that makes a connection using the correct DSN, user, and password using DBI. Apache::DBI is used as well to make the connections persistent, but that is beside the point.
use MyProject::Dbh;
my $dbh = MyProject::Dbh->instance->dbh;
sub method1 {
$dbh->do("... query goes here ...");
}
sub method2 {
my $sth = $dbh->prepare("... another query ...");
$sth->prepare;
#...
}
}
1;
My question, then, what is a better way to manage the connection? Should it be in instance data rather than class data? Should it be set in each method that uses the database (ugly)? I am pleased almost all features of the current approach except for its flaw of never calling connect after initialization (which in Apache::DBI would take care of returning a good connection).