in reply to OO question

As it's written, you actually don't need the new() at all. Any code that wants to use this can just do:

use MyDB; my $dbh = MyDB->dbh();

If there's already been a connection made, it will get the existing $DBH.

Your $DBH variable is a lexical in the scope of the file that your package is in. It starts out as undef, but when you set it, it will stay set. It never goes out of scope and so never loses its value. There's not much more to it than that. Is there some more specific question we can answer than "how does this work"?

I've written code similar to this that seems to work fine under mod_perl with Apache::DBI, but I don't know if I'd call it a best practice.

Replies are listed 'Best First'.
Re^2: OO question
by Anonymous Monk on Mar 18, 2007 at 02:02 UTC
    Your $DBH variable is a lexical in the scope of the file that your package is in. It starts out as undef, but when you set it, it will stay set. It never goes out of scope and so never loses its value.

    I know that $DBH is file lexical and visiable to the MyDB package. but i think the second call to MyDB->dbh is independent to the first one and like a new instance of something.

      but i think the second call to MyDB->dbh is independent to the first one and like a new instance of something.

      New instance of what? $DBH? no.

      { package Cow; my $i; sub moo { print(("moo " x ++$i), "\n"); } } Cow->moo(); # moo Cow->moo(); # moo moo Cow->moo(); # moo moo moo
      { package MyDB; my $DBH; sub dbh { if ($DBH) { print "found existing $DBH\n"; } else { $DBH = 'dbh'; print "Init $DBH\n"; } } } MyDB->dbh(); # Init dbh MyDB->dbh(); # Found existing dbh MyDB->dbh(); # Found existing dbh