简体   繁体   English

Perl class :: dbi - 多个连接

[英]Perl class::dbi - multiple connections

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) 我有一个我在过去几年中开发的类库,它使用Perl的Class :: DBI来包装关系数据库(Prestashop的DB方案,而不重要)

Is anyone aware of anyway in a single perl script to create multiple "instances" of this class, pointing to different database? 是否有人知道在单个perl脚本中创建此类的多个“实例”,指向不同的数据库? Eg 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. 我正在尝试做的主要是别名MyClassLib ,以便能够使用指向不同数据库的另一个“实例”。 Which is a pain as Class::DBI stores its database connection as static state. 由于Class::DBI将其数据库连接存储为静态,因此这很痛苦。

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 . 然后从代码访问MyClassLibMyClassLibAlias Im aware Class::DBI is legacy and a solution that uses DBIx::Class would also be appreciated if non exists for Class::DBI 我知道Class::DBI是遗留的,如果Class::DBI不存在,那么使用DBIx::Class的解决方案也会受到赞赏

Thanks 谢谢

The Class::DBI docs tell you to provide your own db_Main() method in lieu of using connection() . Class::DBI 文档告诉您提供自己的db_Main()方法,而不是使用connection() I believe this could return a standard DBI handle, but Class::DBI uses Ima::DBI internally. 我相信这可能会返回一个标准的DBI句柄,但是Class :: DBI在内部使用了Ima :: DBI。 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. 您可能希望使用类属性引用dsn,用户名和密码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM