Greetings,

I seldom venture in the web end of the Perl pool, but am doing so now and I seek your advice. I'm using Mojolicious and I'm thinking about how to divide up my code. I was thinking of using a module for database functions, but am wondering how I'm going to pass DB handles back and forth. For example:

DB module:

sub new { bless {}; shift } sub connect { my $self = shift; my %param = @_; my $table = "cf_status_log"; my $dbh = DBI->connect( "DBI:Pg:dbname=$param{'db_name'}; host=$param{'db_host'}", "$param{'db_user'}", "$param{'db_pass'}", { RaiseError => 1 } ) or die "Could not connect to database"; return $dbh; }; sub inventory_query { my $dbh = shift; my $result = $dbh->prepare( "SELECT * FROM dr_inventory_classes" ) || die "Could not prepare" ; } 1;

And the main app:

use lib 'lib'; use DeltaR; my $dr = DeltaR->new; sub dbh { my $self = shift; my $dbh = $dr->connect( db_name => "postgres", db_user => "postgres", db_pass => "", db_host => "127.0.0.1" ); return $dbh; }; get '/inventory' => sub { my $self = shift; my $dbh = dbh; my $rows = $dr->query_inventory( $dbh ); $self->stash( title => "Inventory report", record_limit => $record_limit, rows => $rows, columns => [ 'Count', 'Class' ] ); } => "rtable"; app->start;

I don't want to make unneeded connections because not all pages will require the database. I don't know if handle passing like this is the best approach. How would you do it? Passing $dbh around is a bit fiddly. Is there a better way?

Neil Watson
watson-wilson.ca


In reply to Seeking guidance for web/db application by neilwatson

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.