Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Problem managing persistent database connections in modules

by mfriedman (Monk)
on Jul 25, 2002 at 20:17 UTC ( #185320=note: print w/replies, xml ) Need Help??

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://185320]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (2)
As of 2021-06-18 03:09 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (87 votes). Check out past polls.