fx has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I am using the DBI module to enable me to use a PostgreSQL database in several Perl programs. My programs have several Perl source files drawing common data from a package file.

In the package file, let's say MyPackage.pm, I get a database hadler for use inside the package, $dbh, by issuing $dbh = DBI->connect(...). I also have an exported function in MyPackage.pm called getDbRef() which returns a reference to $dbh.

When my source code files need to use the database, to execute an INSERT statement for example, sometimes they call an exported function from MyPackage.pm (which in turn would call $dbh->do($sql) or something) and sometimes they use the exported reference directly ($$dbh->do($sql) or something).

My question: is one of my methods better than the other? If so, why?

Thanks,

fx

Replies are listed 'Best First'.
(Ovid) Re: Using DBI: handlers or references to handlers?
by Ovid (Cardinal) on Sep 16, 2001 at 01:23 UTC

    First, since the DBI object ($dbh) is already a reference, there is no problem returning this instead of a reference to it. In fact, I would think this preferable since there is no need to return a reference to a reference. Generally (though not always), one returns a reference to data due to the overhead of passing the data itself. Since you already have a reference, that overhead is avoided.

    As for your actual question, I understood you to ask whether using the exported function or using the returned database handle is preferable. My opinion is that you should not even return a database handle. Isolate your code from the database.

    As an example, I am currently working on a Web site administrative package for a company that allows them to manage most of the content of their Web site through a convenient Web interface. Naturally, this relies heavily on a database. However, you will not see a single line of SQL in any of the programs that my coworkers are writing. There is absolutely nothing database dependant in any of them (the programs, not the coworkers :). Instead, I have created some modules that interact with the database and all programmers writing the programs use the objects (in your case, functions) that are made available. Why is this important? Because if we need to make changes to the database, we there are only three modules that contain all database dependant code (one for information retrieval, one for modifications, and the other for security, all with an appropriate level of permissions).

    At last count, excluding the modules, we had about 30 different programs on this system. Can you imagine the havoc caused by updating the database and having to search through 30 programs for anything that touches the database?

    Cheers,
    Ovid

    Vote for paco!

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.