gryphon has asked for the wisdom of the Perl Monks concerning the following question:
Greetings fellow monks,
I'm playing around with Class::DBI again, and I'd really like to pass dynamic DSNs and other database connection information to my parent class from the calling script or application module. I've been using Config::IniFiles for a while now, and I really like it and would like to continue to use it. I've been toying with a few ideas on how to combine my various wants, and here's what I've come up with.
#!/usr/bin/perl use strict; use warnings; use Config::IniFiles; my $cfg; BEGIN { $cfg = new Config::IniFiles( -file => 'settings.ini' ); $ENV{_MyCDBI} = join("\t", $cfg->val('Database', 'dsn'), $cfg->val('Database', 'Username'), $cfg->val('Database', 'Password') ); } use MyCDBI;
I'm using use here just because it's habit and because it runs parallel to using other CPAN stuff and my own application modules. However, I could just as easily require instead of use to simplify things.
my $cfg = new Config::IniFiles( -file => 'settings.ini' ); $ENV{_MyCDBI} = join("\t", $cfg->val('Database', 'dsn'), $cfg->val('Database', 'Username'), $cfg->val('Database', 'Password') ); require MyCDBI;
Either way, I just split the various bits inside my Class::DBI parent.
package MyCDBI; use base 'Class::DBI::mysql'; __PACKAGE__->connection(split("\t", $ENV{_MyCDBI}));
Now, this works just fine, and I'm more or less happy with it for my purposes, but it's far from optimum. First of all, I'm using poor-man's serialization of the bits for the database connection. A better solution would include the capability of sending stuff like {AutoCommit => 1} and whatever else. Plus, the code in the calling script is somewhat obnoxious. I'd love to use use if possible, but even without, it's three lines long. I know if merlyn saw this, he'd cringe and use a one-liner alternative.
So my question is thus: What are some better ways of doing this? (Better = less lines of code, more flexible data sent, more class encapsulation, more coffee, etc.) One thing I was thinking about was writing an abstraction class for my parent Class::DBI class. I've always hated having to refer to the subclass names multiple times.
my $obj = MyCDBI::SomeDBObj->retrieve(1); # versus my $cls = new MyCDBI; my $obj = $cls->SomeDBObj->retrieve(1);
But I can't really say exactly why I don't like this.
I've been reading about Class::DBI::Factory, but I have to admit that much of it goes way over my head. Should I just grin and deal with the learning curve? Or is there a simpler way?
gryphon
code('Perl') || die;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Abstracting Class::DBI Database Connection Data
by hardburn (Abbot) on Jun 08, 2004 at 20:40 UTC | |
by gryphon (Abbot) on Jun 08, 2004 at 22:15 UTC | |
by dcvr69 (Beadle) on Jun 08, 2004 at 22:20 UTC | |
by gryphon (Abbot) on Jun 08, 2004 at 22:44 UTC | |
by perrin (Chancellor) on Jun 09, 2004 at 00:16 UTC | |
|