I'm fairly new to Moose and use DBI occasionally. I'd like to get some input on a Moose::Role I've written to make it easier for objects to change the database handler. I'm probably reinventing the wheel but at least I'm learning something. Here's a chunk of the code:
package DB;
use DBI;
use Carp;
use Moose::Role;
use Modern::Perl;
has 'db' => ( is => 'rw', isa => 'Str', lazy => 1, default =>
+ '', trigger => \&_switch_db );
has 'dbh' => ( is => 'rw', isa => 'DBI::db', lazy => 1, builder =>
+ '_db_connect' );
has 'dsn' => ( is => 'rw', isa => 'Str', lazy => 1, default =>
+ 'DBI:mysql:host=127.0.0.1');
has 'db_user' => ( is => 'rw', isa => 'Str', lazy => 1, default =>
+ 'root' );
has 'db_pass' => ( is => 'rw', isa => 'Str', lazy => 1, default =>
+ 'mypass' );
has 'db_host' => ( is => 'rw', isa => 'Str', lazy => 1, default =>
+ '127.0.0.1' );
has 'db_type' => ( is => 'rw', isa => 'Str', lazy => 1, default =>
+ 'mysql' );
sub _db_connect {
my $self = shift;
my $db = shift;
$self->_set_dsn($db);
return DBI->connect($self->dsn, $self->db_user, $self->db_pass) || l
+ogf("Can't connect to database $db");
}
sub _set_dsn {
my $self = shift;
my $db = shift;
logd('setting database');
my $dsn = 'DBI:' . $self->db_type . ':host:' . $self->db_host;
$dsn .= ";database=$db" if $db;
$self->dsn($dsn);
}
sub _switch_db {
my $self = shift;
logd('switching db');
$self->dbh($self->_db_connect($self->db));
}
Before I use this role too much, I'd like to get some input from more seasoned Monks as to whether I'm doing anything foolish (I've learned I usually do). Of particular concern is the creation of a new database handler when simply switching the database using the 'db' attributes 'trigger' method.
Thanks!