in reply to need help developing fly OO style

Well, it depends. In your second code example, that makes it look as if you're calling my_function on your $DBH object. You can't do this unless you've defined my_function to be in the class into which your database handle is blessed (or in some ancestor of that class). In your case, that ancestor would be DBI. I'm not sure that inheriting from DBI would be particularly easy, considering that it relies on specific database drivers to do much of the work. So in that case, what exactly are you inheriting from: DBI or the database driver?

Here's what I've done in the past, which makes it easier. I use a "has-a" relationship rather than an "is-a" relationship.

I've created a My::DBI class (or something such). An object of type My::DBI contains a DBI database handle; but it's not actually a database handle itself. Every method that I call on my database handle is forwarded to a call on the database handle; before and after this forwarding I can do some processing on my own. For example (this code is untested, though it's based from memory on code I've written before, which *is* tested):

package My::DBI; use strict; sub new { my $class = shift; bless { @_ }, $class; } sub connect { my $self = shift; return $self->{dbh} if defined $self->{dbh}; croak "Need connection parameters" unless defined $self->{connect}; my $c = $self->{connect}; ## Simplify typing :) return $self->{dbh} = DBI->connect ($c->{dsn}, $c->{user}, $c->{pass}, 'mysql', { RaiseError => 1 }); } sub my_function { my $self = shift; ## $DBH is now in $self->{dbh} } ...
And so on. Usage:
my $db = My::DBI->new(connect => { ... }); $db->my_function(@args);
Would that work for you?

Replies are listed 'Best First'.
RE: My::DBI solution
by markjugg (Curate) on Aug 12, 2000 at 12:25 UTC
    Thanks btrott, After some contemplation, I don't think this is my ideal solution, though I can see it's benefit in other situations. Say for example my module I'm building is named CGI::SQL, I'd like it to have functions that use the $dbh, but it doesn't try to connect itself-- a connection is already assumed-- this gets me out of the business of managing the user's preferences for their connect string. maybe just passing in the $dbh as a normal function argument is the way to go?