Date: Tue, 25 Aug 2015 11:45:28 +0100
From: Andrew Beverley <andy@andybev.com>
To: Perl Dancer users mailing list <dancer-users@dancer.pm>
Subject: Re: [dancer-users] database connection in dancer
Message-ID: <1440499528.28975.7.camel@andybev.com>
Content-Type: text/plain; charset="UTF-8"

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

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.

 I am using Dancer.

 
> 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.

I  would like to know how to make one db connection and use it in all requests. where to store  the database handler?  

 
> 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';

Andy