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?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.