Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: How to dynamically invoke one of several similarly named modules

by stevieb (Canon)
on Aug 22, 2022 at 18:14 UTC ( [id://11146296]=note: print w/replies, xml ) Need Help??


in reply to How to dynamically invoke one of several similarly named modules

If all the classes do exactly the same thing except they point to a different database, then the way you propose seems to be a whole lot of code duplication across several files for no reason (this will become a maintenance and testing nightmare).

I'd create a single class/module, and select the database when loading the module (or on object creation) based on whatever condition you need (environment variable, object instantiation parameter etc). For this, you can use if statements, a dispatch table etc.

Using if statements or a dispatch table is by far more elegant than having multiple modules all doing the same thing. Besides, even in your example you posted, you're still going to have to use if statements; at the module loading level instead of database selection level.

Replies are listed 'Best First'.
Re^2: How to dynamically invoke one of several similarly named modules
by onemojofilter (Novice) on Aug 22, 2022 at 18:21 UTC

    Yes, that does sound more reasonable. I was stuck on the examples I was shown but I suppose I needed a second pair of eyes.

    Much appreciated!

      The pseudo-code for the way I imagine implementing this is something like:

      use DataBaseDriver; ... use constant CITIES => qw(lon par); use constant APPLICATIONS => qw(test prod); # build dispatch table for database handles my %db_handle; for my $city (CITIES) { for my $app (APPLICATIONS) { $db_handle{$city}{$app} = DataBaseDriver->new or die "'$city:$app' driver creation failed: ", DataBaseDriver->error_msg; } } ... # use database handle dispatch table my $msg = '...'; my $city = '...'; my $app = '...'; my $dbh = $db_handle{$city}{$app} or die "'$city:$app' driver access failed"; $dbh->store_to_database($msg); ...


      Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11146296]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-03-29 01:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found