Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Re: Object Oriented Pattern help

by steveAZ98 (Monk)
on May 12, 2001 at 10:21 UTC ( #79918=note: print w/replies, xml ) Need Help??

in reply to Re: Object Oriented Pattern help
in thread Object Oriented Pattern help

I agree here, I open a connection to the database in the constructor and disconnect in the destructor. If your running mod_perl you'll most likely have cached open handles which can be used and you might not need the disconnect, but I do it out of habit. I use code something like this:
use vars qw( %conn ); sub new { my $class = shift; $self = bless { _dbh => undef, }, $class; $conn{'dbname'} ||= DBI->connect( ... ); $self->dbh( $conn{'dbname'} ); return $self; } sub DESTROY { $_[0]->dbh->disconnect() if $_[0]->dbh; } sub dbh { @_ > 0 ? $_[0]->{_dbh} = $_[1] : $_[0]->{_dbh} }

Replies are listed 'Best First'.
Re: Re: Re: Object Oriented Pattern help
by koolade (Pilgrim) on May 12, 2001 at 18:04 UTC

    This may not be so good of an idea if using multiple instances of the class in a single program. Even with persistent connections, it seems too cumbersome to pass in database info to the constructor each time. If you're not using persistent connections and you create 5 objects in a script, each object will create a new connection to the database.

    This also doesn't scale very well if using another similar class in the program. Again, multiple handles to the same database for each guest object and each XYZ object and you have some pretty greedy perl code.

    If you're only using one class to access the database, then maybe use a class variable:

    package Guest; use vars qw($DBH); sub new { $DBH ||= DBI->connect(...); } END { $DBH->disconnect(); }

    The original code showed passing in a reference to the database handle to each method and that would work fine. A better way may be to pass that in to the constructor and have each object store that instead. But if you do that, make sure you don't have the destructor close the database handle either. Doing database opens/closes in a central location (in this case, the main program) seems like the cleanest way.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2022-10-06 20:29 GMT
Find Nodes?
    Voting Booth?
    My preferred way to holiday/vacation is:

    Results (28 votes). Check out past polls.