Trihedron
Trihedron

Reputation: 276

Perl Modules - Sharing Database Connection

Can someone give me some direction on the best way to do when sharing a $dbh variable between "objects" in different .pm files.

For instance, my main module say Foo.pm has a new constructor, etc and I could give it a dbh or create a dbh and then share it by passing it as a parameter to the new constructor for Bar.pm, and then re-assigning inside Bar->new, but that seems like I'm doing a lot of work managing this variable.

Is this a simple, yet elegant way to do this? I've researched Exporter and a few other examples, but none seem to be straight forward.

Thanks!

Upvotes: 2

Views: 615

Answers (2)

Artyom V. Kireev
Artyom V. Kireev

Reputation: 628

I suppose that what you actually want is to take the control over $dbh creation out of the code that works with it. Most trivial way is, well,

my $dbh;
sub get_dbh {
    if ( $dbh is bad ) {
       reconnect or whatever
    }

    return $dbh || die;
}

And then in your code access it like

get_dbh()->do("your sql");

You could put that get_dbh() function to a separate module and call it from anywhere in your project - as usual with perl, it will be included only once and its local static variable $dbh will exist in only one copy within the perl process.

There are many possible ways to achieve that, writing a function like described above (and maybe passing a reference to that function instead of passing the $dbh) is one. There are plenty of others, depending on your design and personal taste - a singleton class, a variable tied to the function described above, or even a class that imitates DBI... That's up to you, but that should be one piece of code, spreading this logic all over your project is a bad idea.

Upvotes: 2

Miguel Prz
Miguel Prz

Reputation: 13792

If you're using Moose to build your object, you could encapsulate your database handle in a role and require it into classes that need the database access.

Upvotes: -1

Related Questions