in reply to Re: Re: Database Connections
in thread Database Connections

Actually, Fastolfe's suggestion allows you to only create a single DB connection for the life of the script.

The first time new MyDBLayer is called, the variable $dbh will be undef, so a database connection will be created. The second time new MyDBLayer is called, $dbh will already hold a database object; that object will be returned, instead of a new connection being made.

The key is the use of the ||= operator; a new database connection will be made only if $dbh doesn't already hold a database object.

Personally, I've used the approach of passing a database connection into a subroutine, but I really like Fastolfe's approach.