in reply to Moose::Role to provide DBI interface

Hi nysus,

It's hard for me to imagine when you'd want to change the DB connection attribute of an object instance. If you really need more than one connection, it might be better to hide them in the consuming class behind object methods that simply return the data you want.

On the other hand it *is* common to need to connect to more than one DB in a given application. In that case (or in the case of a single object needing more than one connection) I would suggest using an external configuration file with the configs for your various DSNs, and then create your single class that will return a DB connection based on the parameters passed. I wouldn't try to switch connections as you've outlined, seems too error-susceptible and for no real benefit. Other monks may be able to provide the nitty-gritty as to why it's a bad idea; all I can say is that it smells dodgy.

Hope this helps!


The way forward always starts with a minimal test.
  • Comment on Re: Moose::Role to provide DBI interface

Replies are listed 'Best First'.
Re^2: Moose::Role to provide DBI interface
by nysus (Parson) on Feb 08, 2017 at 20:48 UTC

    My objectives here are 1) less typing to set up a $dbh and 2) get practice with Moose. Just about 100% of the time my scripts are for my own purposes. So I have this role set up with defaults that I will probably use 99% of the time. I can always change them later if I need to. So now I can write one liner like this:

    use LaborData::Data::SchemaLoader; my $loader = LaborData::Data::SchemaLoader->new; $loader->make_schema('lm2_data');

    LaborData::Data::SchemaLoader contains DBIx make_schema method and my DB package which automatically loads a database handler. And so now I never have to look up the code again for loading a schema for DBIx when I want to do it on a different database.

    But you are right. It's doubtful I would ever need to have my object switch the db connection.

    This didn't smell good to me either. That's why, I suppose, I asked this question. I like your suggestion of a configuration file. That does seem like the proper, more extensible way of doing things. I'm sure there's a module for that. But I got enough on my plate already. :)

    Thanks for the feedback.

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

      "And so now I never have to look up the code again for loading a schema for DBIx when I want to do it on a different database."

      This makes zero sense. Why would you "load" a schema? What does that even mean?

        Don't know for sure. Just learning DBIx. Apparently it generates a bunch of files that contain meta data about the database.

        $PM = "Perl Monk's";
        $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
        $nysus = $PM . ' ' . $MCF;
        Click here if you love Perl Monks