[dancer-users] database connection in dancer

Andrew Beverley andy at andybev.com
Tue Aug 25 11:45:28 BST 2015

On Tue, 2015-08-25 at 11:38 +0100, Dancer New wrote:
> Hi,


> I am trying to implement a user login on a website.
> Each time a user logon, the session record the user name.

Firstly, have you considered using an existing authentication module, such as
Dancer2::Plugin::Auth::Extensible? This will save reinventing the wheel.

> The problem I have now was the database connection in 'before hook' (
> setting user context) and the db connection in the route for actual query
> seems two different db connections. So the database doesn't know they are
> from the same user request and therefore doesn't return the right results.

It sounds like you are initiating a new database connection for each page request?
If so, that's very expensive, and not likely to be very scalable.

> How to keep the database connection in 'before hook' and pass the same
> database connection to other route?

If you still decide to do it this way, then you could save the database connection
using var and then read that value later:

    var mydb => $db;
    my $db = var 'mydb';


More information about the dancer-users mailing list