Skip to content

Instantly share code, notes, and snippets.

@sgnix
Last active December 20, 2015 17:38
Show Gist options
  • Save sgnix/6169641 to your computer and use it in GitHub Desktop.
Save sgnix/6169641 to your computer and use it in GitHub Desktop.
Connecting to DBI in Kelp
package MyApp;
use Kelp::Base 'Kelp';
use DBI;
# Lazy attribute with DBI handle
attr _dbh => sub {
$_[0]->_dbi_connect;
};
# Private sub to connect
sub _dbi_connect {
my $self = shift;
my @config = @{ $self->config('dbi') };
DBI->connect(@config);
}
# Public method to use when you need dbh
sub dbh {
my $self = shift;
if ( !$self->_dbh->ping ) {
$self->_dbh( $self->_dbi_connect );
}
$self->_dbh;
}
# Use $self->dbh from here on ...
sub some_route {
my $self = shift;
$self->dbh->selectrow_array(q[
SELECT * FROM users
WHERE clue > 0
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment