in reply to Problem managing persistent database connections in modules

I have set up a rather simple "singleton" type class to share a single database connection among several objects (about 20 in all) in a large application. The code I used follows the examples in Damian Conway's excellent book about OO Perl.

pacakge MyProject::DBH; use DBI; my $DBH; # lexical scope outside the constructor # makes it available to all calls to new(). sub get_dbh { if ref($DBH) eq 'DBI::db') { # dbh already created, so return it return $DBH; } else { # connect to the DB and return the handle # (assume $user, $pass and $dsn come from somewhere) $DBH = DBI->connect($dsn, $user, $pass); return $DBH; } }

Then, it's just a simple matter of every object calling MyProject::DBH->get_dbh; to get the same database handle.

Replies are listed 'Best First'.
Re: Re: Problem managing persistent database connections in modules
by mp (Deacon) on Jul 26, 2002 at 00:24 UTC
    Could you give an example of where you call MyProject::DBH->get_dbh in a module and where you store the database handle? I.e., do you call it from the constructor then store the database handle in the object as instance data, or do you call it from each object method that needs a database handle?
      In that project, I had each class which needed access to the DB call MyProject::DBH->get_dbh in its constructor and store the returned database handle in the instance data. Then, it's available for each method that needs it in $self->{'dbh'}.

      You could just as easily make the DBH a package variable, but doing it this way seemed "neater" despite the increaed number of calls to get_dbh.