Last active
December 20, 2015 17:38
-
-
Save sgnix/6169641 to your computer and use it in GitHub Desktop.
Connecting to DBI in Kelp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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