【问题标题】:using a subroutine in the new() method using perl Moo在使用 perl Moo 的 new() 方法中使用子例程
【发布时间】:2016-04-15 20:32:10
【问题描述】:

我的问题如下:当我调用 new() 方法使用 perl Moo 创建对象时,我想使用一个子例程来构造一个数组。请看下面的例子。

package Customer;
use DBI;
use 5.010;
use Data::Dumper;
use Moo;
use FindBin qw/$Bin/;
use lib "$Bin/../../../lib";
use lib '/home/fm/lib';
use TT::SQL;

has id => (
  is=>'ro',
  required=>1,
);

has type => (
  is=>'ro',
);

has emails => (
  is=>'rw',
  isa => sub {getEmails() },
);

sub getEmails
{
                #connecting into de DB
                my $self=shift;
                my $db2 = TT::SQL::get_handler("xxxxxx","xxxxx");
                my $fmuser=$self->id;
                my $type=$self->type;
                my $query;
                #checking the customer type to perform the query
                if ($type eq "xxxxxxxxxx")
                {
                $query=xxxxxxxxxxxxxx;
                }
                else
                {
                $query=xxxxxxxxxxxxxx;
                }
                my $ref = $db2->execute($query,$fmuser);
                my @emails;
                #retrieving emails
                while ( my $row = $ref->fetchrow_hashref  ) {
                       @emails=(@emails,"$row->{email}\n");
                  }
                return @emails;
}

1;

基本上,我正在尝试从数据库中检索一些电子邮件,并且不用担心查询和数据库访问,因为当我执行以下操作时:

my $cc= Customer->new(id=>92,type=>'xxxxxxx');
@emails=$cc->getEmails();

@emails 中的结果是预期的。但是,当我执行时:

my $cc= Customer->new(id=>92,type=>'xxxxxxx');
@emails=$cc->emails;

我什至没有结果。

如果我能得到这个问题的答案,我将不胜感激。在此先感谢各位。

【问题讨论】:

    标签: perl oop constructor moo


    【解决方案1】:

    您想使用构建器方法或默认方法,isa 用于强制类型约束:

    默认值:

    has emails => (
      is      => 'rw',
      default => sub { 
         my ($self) = @_;
         return $self->getEmails();
      },
    );
    

    建造者:

    has emails => (
      is      => 'rw',
      builder => '_build_emails',
    );
    
    sub build_emails {
        my ($self) = @_;
    
        return $self->getEmails();
    }
    

    如果getEmails() 子例程需要任何额外的启动时间(例如获取数据库句柄),我还建议将lazy => 1 参数添加到您的电子邮件属性中。这只会在它调用时初始化它。

    【讨论】:

    • lazy 在这种情况下必须设置为1,因为getEmails 依赖于type(来自文档:请注意,如果在 new()无法保证其他属性已被填充,因此您不应依赖它们的存在。)。此外,builder 参数可以直接设置为getEmails,而不是使用中间值。
    • 你们是最棒的人!感谢您的回答,我已经解决了我的问题。非常感谢。
    • @ccalderon911217 您可以通过点击上面的复选标记来接受答案,这将使以后遇到此问题的用户知道这解决了您的问题
    猜你喜欢
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2012-03-24
    • 2013-02-16
    • 1970-01-01
    相关资源
    最近更新 更多