frazap has asked for the wisdom of the Perl Monks concerning the following question:
+lib MyLib.pm +MyLib +Controller Invtot.pm +public js files... +script my_lib.pl +t basic.t +templates .... +layouts ....
It's composed of two pages, one with a form that need to connect to a database. I will a add an other form in a third page, that will connect to a second database. I came with the following (that works) to connect to my first db :
That way I could connect to different db without having all the connection done in the startup
The main module MyLib.pm isMy question: even if that works, is there something that could break in the long term, something I forgot here?package MyLib; use Mojo::Base 'Mojolicious'; my %connections; # This method will run once at server start sub startup { my $self = shift; # Router my $r = $self->routes; # Normal route to controller $r->get('/')->to( template => 'index' ); $r->get('/libmap'); #->to(controller => 'libmap'); $r->get('/invtot')->to( controller => 'invtot', title => 'Paper journals from the library', cb => sub { $self->connect_invtot() } ); if ( exists $ENV{PAR_TEMP} && $^O eq "MSWin32" ) { system qw(start http://localhost:3000/invtot); } $r->post('/invtot')->to( controller => 'Invtot', action => 'post' +); } sub connect_invtot { my $self = shift; return if $connections{db1}; # Load configuration from hash returned by config file my $file; if ( $ENV{PAR_TEMP} ) { print $ENV{PAR_TEMP}, "\n"; $file = $ENV{PAR_TEMP} . "/inc/script/my_lib.conf"; } else { $file = 'my_lib.conf'; } my $config = $self->plugin( 'Config', { file => $file } ); # Configure the application $self->secrets( $config->{secrets} ); $self->log->debug("connecting..."); $self->plugin( 'Database', { dsn => 'dbi:mysql:host=mysql....:dbname=d....', username => $config->{username}, password => $config->{password}, options => { 'pg_enable_utf8' => 1, AutoCommit => 1, PrintError => 0, RaiseError => 1 }, helper => 'db1', } ); $connections{db1} = 1; } 1;
Thanks
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Mojolicious and connection to a database
by trippledubs (Deacon) on May 03, 2019 at 12:16 UTC | |
by frazap (Monk) on May 03, 2019 at 13:02 UTC | |
by bliako (Abbot) on May 04, 2019 at 08:05 UTC | |
by trippledubs (Deacon) on May 03, 2019 at 14:26 UTC | |
|
Re: Mojolicious and connection to a database
by Anonymous Monk on May 06, 2019 at 16:41 UTC | |
by frazap (Monk) on May 08, 2019 at 06:24 UTC |