Reputation: 333
I have a class library I have developed over the last few years that uses Perl's Class::DBI to wrap a relational database (the DB scheme for Prestashop, not that that matters)
Is anyone aware of anyway in a single perl script to create multiple "instances" of this class, pointing to different database? E.g. now I do something like:
use MyClassLib;
MyClassLib->connection('dbi:mysql:mydatabase', 'username', 'password');
MyClassLib->some_method()
All that works nicely.
What I'm trying to do is essentially alias MyClassLib
to be able to use another "instance" of it pointing at a different database. Which is a pain as Class::DBI
stores its database connection as static state.
Something like this in pseudo code
use MyClassLib;
use MyClassLib as MyClassLibAlias;
MyClassLib->connection('dbi:mysql:mydatabase', 'username', 'password');
MyClassLibAlias->connection('dbi:mysql:mynewdatabase', 'username', 'password');
MyClassLib->some_method()
And then from code access MyClassLib
and MyClassLibAlias
. Im aware Class::DBI
is legacy and a solution that uses DBIx::Class
would also be appreciated if non exists for Class::DBI
Thanks
Upvotes: 3
Views: 352
Reputation: 4371
The Class::DBI
docs tell you to provide your own db_Main()
method in lieu of using connection()
. I believe this could return a standard DBI handle, but Class::DBI uses Ima::DBI internally. You could use a single class for this, but to mirror your pseudo code:
package MyClassLibAlias;
use base qw(MyClassLib);
sub db_Main {
my $self = shift;
my ($dsn, $username, $password) = ...;
return Ima::DBI->connect_cached($dsn, $username, $password);
}
You'll likely want to reference the dsn, username and password using class attributes.
Upvotes: 3