【问题标题】:Is there a way to set inheritance in the same module with __PACKAGE__->?有没有办法用 __PACKAGE__-> 在同一个模块中设置继承?
【发布时间】:2013-04-23 20:15:43
【问题描述】:

例如,我想在启动时存储 dbi 连接的数据,这样我就不必通过对象对其进行初始化,他们是否可以在同一个包中执行此操作?

通过我的对象初始化将是:

my $obj = foo->new;
my $dbh = $obj->connect('dbi', 'user', 'pw');

但我想在启动时将它存储到我可以使用的地方

my $obj = foo->new;
my $blah = $obj->selectall_arrayref(...);


package foo; 

use strict; 
use warnings;  

__PACKAGE__->connect('dbi', 'user', 'pw');    

sub new {   
 my $class = shift;   
 my $self  = {};   
 bless ($self, $class);   
 return $self; 
}   

 sub connect {   
  my $class = shift;   
  my $self  = ref $class || $class;   
  return $self->(@_);     # Is this possible? 
 }

【问题讨论】:

    标签: perl class inheritance constructor dbi


    【解决方案1】:

    使用代理对象的替代方法是简单地将 DBI 组合到您的类中。

    package foo;    
    use DBI;
    
    sub new {   
        my $class = shift;
        my $self  = {DBH => DBI->connect(@_)};   
        bless ($self, $class);   
        return $self; 
    }
    
    # defer method call to DBH
    sub selectall_arrayref {shift->{DBH}->selectall_arrayref(@_)}
    
    package main;    
    my $obj = foo->new('dbi:...', 'user', 'password');
    my $blah = $obj->selectall_arrayref(...);
    

    【讨论】:

      【解决方案2】:

      子类化 DBI 类并不简单,只需 read the documentation。 其他方式可能是声明一个proxy object,并在AUTOLOAD的帮助下调用被包装的对象。

      【讨论】:

        猜你喜欢
        • 2022-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-28
        • 2011-02-16
        • 2011-01-14
        • 1970-01-01
        • 2011-03-08
        相关资源
        最近更新 更多