http://www.perlmonks.org?node_id=347744

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

Greetings fellow monks,

I've been trying unsuccessfully to play with Class::DBI using a dynamic DSN passed to my class at runtime. I've been Googling for hours, and I haven't come up with much to show for it. Does anyone have some example code they could share for how to get this done?

This is basically what I'd like to accomplish, but it doesn't work. (Please pardon my lack of POOP knowledge/experience.)

package Stuff; use base 'Class::DBI::mysql'; sub import { my $class = shift; unless (__PACKAGE__->can('db_Main')) { __PACKAGE__->set_db('Main', @_); } } package Stuff::Item; use base 'Stuff'; __PACKAGE__->set_up_table('item'); package main; use Stuff ('dbi:mysql:dbname', 'gryphon', 'password'); my $item = Stuff::Item->retrieve(1); print $item->name, "\n";

Why do I even want to do this? Well, I have multiple databases all with the same schema. I'd like to have only one Class::DBI module to avoid replicating code. And I'd like to pass in the database name, username, and password from an INI file since that's where just about all other configuration data is stored.

Now, I've tried the following:

use Class::DBI::AutoLoader ( dsn => 'dbi:mysql:dbname', username => 'gryphon', password => 'password', tables => ['item'], namespace => 'Stuff', use_base => 'Class::DBI::mysql' ); my $item = Stuff::Item->retrieve(1); print $item->name, "\n";

...and of course this works well, but it will only work for very simple models. I won't be able to edit the automatically created classes, so it doesn't work for more complicated cases such as where I'm joining together several tables or want to muck around with output or whatever.

Sorry if this is a stupid question. I've been reading docs all day and haven't been able to figure this out.

gryphon
code('Perl') || die;