5

Is there a way to pass additional variables to a method handler subroutine? I generally dislike using global variables outside the subroutine's scope. I have things like database connection and class instances which I would like the handlers to have access to, without using globals. Using debug to console, looks like @_ is empty for each handler call.

#!/usr/bin/perl

use strict;

use Dancer;
use Data::Dumper;

set('logger' => 'console');

my $somevar = SomeClass->new();

get('/' => sub{
  debug(Dumper(@_));
  debug($somevar);
  return('hello world');
});
Douglas Mauch
  • 859
  • 2
  • 7
  • 18

2 Answers2

3

One way is to use the vars hash that Dancer provides. Here I use a before hook to set up a database handle:

use strict;
use warnings;
use Dancer;
use DBI;

hook 'before' => sub {
    var dbh => DBI->connect_cached(...);
};

get '/' => sub { 
    my $qry = vars->{dbh}->prepare("SQL");
    ...
    return "Something, something, query results";
};
friedo
  • 65,762
  • 16
  • 114
  • 184
RickF
  • 1,812
  • 13
  • 13
  • Not sure that will work for my application. It looks like before runs on every match before the main handler routine. Some of the variables I want to use are one time setup kinda stuff. They include class instances, which I don't want to reinitialize on every http method call to dancer. I wish there was something else like this, but was only ever called once. – Douglas Mauch Apr 12 '13 at 15:19
  • I also tried using "vars" outside the hook. It doesn't complain. But the value is not there when inside the method handler. – Douglas Mauch Apr 12 '13 at 19:24
  • 'Only ever called once' and 'class instances' sound like you might just want to use package variables. Something like `our $dbh = DBI->connect();`, declared outside of any handlers. – RickF Apr 12 '13 at 21:50
0

With something like

sub get_dbh {
    if (! vars('dbh')) {
        my $dbh = DBI->connect_cached(...);
        session(dbh => $dbh);
    }
    return vars('dbh');
}

you have access to the database handle from anywhere without it being global, the database connection is not made until you need it and, if you need it again later in your program, is still in the vars collection and does not need to be created again.

neniu
  • 419
  • 3
  • 8