Moose从单个参数构造对象

时间:2015-06-26 12:19:11

标签: perl moose type-constraints

我已经和Moose讨论了大约七个月而且Perl只是稍长一点,但是无法通过为每个属性提供一个参数来解决如何在类中构造多个属性,而不是他们的整个hashref。我已经广泛搜索了文档和网页,但我要么找错了字,要么遗漏了什么。

我已经使设计更加通用。通过以下基本设置:

package First;
use Moose;
use Second::Type1;
use Second::Type2;
has 'type1' => (
  is => 'rw',
  isa => 'Second::Type1',
  default => sub {Second::Type1->new(name => 'random')}
);

has 'type2' => (
  is => 'rw',
  isa => 'Second::Type2',
  default => sub {Second::Type2->new(name => 'random')}
);

package Second::Type1;
use Moose;
use This;
has 'name' => (
  is => 'rw',
  isa => 'Str',
  required => 1,
);
has 'this' => (
  is => 'rw',
  isa => 'This',
  default => sub {This->new()}
);
# package has more attributes, but you get the idea
__PACKAGE__->meta->make_immutable();
no Moose;
1;

package Second::Type2;
use Moose;
use That;
has 'name' => (
  is => 'rw',
  isa => 'Str',
  required => 1,
);
has 'that' => (
  is => 'rw',
  isa => 'That',
  default => sub {That->new()}
);
# package has more attributes, but you get the idea
__PACKAGE__->meta->make_immutable();
no Moose;
1;

我希望能够通过说:

来构建First
use First;
my $first = First->new(type1 => 'foo', type2 => 'bar');

其中' foo'等于Second :: Type1' name'的值属性和' bar'等于Second :: Type2' name'的值属性。

就我自己的解决方案而言,我已经(成功)制作了一个Moose :: Role,它只包含一个围绕着BUILDARGS' sub然后使用Factory类(其内容与IMO相关):

package Role::SingleBuildargs;

use Moose::Role;
use Factory::Second;
requires 'get_supported_args';

around BUILDARGS => sub {
my ($class, $self, %args) = @_;
my @supported_args = $self->get_supported_args;
my $factory = Factory::Second->new();
    my @errors = ();
    foreach my $arg (sort {$a cmp $b} keys %args) {
        if (grep {$_ eq $arg} @supported_args) {
            my $val = $args{$arg};
            if (!ref $val) {    # passed scalar init_arg
                print "$self (BUILDARGS): passed scalar\n";
                print "Building a Second with type '$arg' and name '$val'\n";
                $args{$arg} = $factory->create(type => $arg, name => $val)
            } elsif (ref $val eq 'HASH') {  # passed hashref init_arg
                print "$self (BUILDARGS): passed hashref:\n";
                my %init_args = %$val;
                delete $init_args{name} unless $init_args{name};
                $init_args{type} = $arg;
                $args{$arg} = $factory->create(%init_args);
            } else {    # passed another ref entirely
                print "$self (BUILDARGS): cannot handle reference of type: ", ref $val, "\n";
                die;
            }
        } else {
            push @errors, "$self - Unsupported attribute: '$arg'";
        }
    }
    if (@errors) {
        print join("\n", @errors), "\n";
        die;
    }
    return $self->$class(%args);
    };

no Moose;
1;

然后我在First类和其他类中使用该角色,如First。

我也尝试过胁迫:

package Role::Second::TypeConstraints;
use Moose::Util::TypeConstraints

subtype 'SecondType1', as 'Second::Type1';
subtype 'SecondType2', as 'Second::Type2';
coerce 'SecondType1', from 'Str', via {Second::Type1->new(name => $_};
coerce 'SecondType2', from 'Str', via {Second::Type2->new(name => $_};

no Moose::Util::TypeConstraints;
1;

并修改了第一个包(仅列出了更改):

use Role::Second::TypeConstraints;
has 'type1' => (
   isa => 'SecondType1',
   coerce => 1,
);
has 'type2' => (
   isa => 'SecondType2',
   coerce => 1,
);    

然而,这并没有奏效。如果有人能解释原因,那就太好了。

关于实际问题:在课堂上获得这种行为的最佳方法是什么?真的没有比修改BUILDARGS更好的方法了,或者我错过了什么(关于Moose :: Util :: TypeConstraints,也许)? TMTOWTDI和所有,但我的效率根本不高。

编辑:编辑一致性(混合通用类名)

2 个答案:

答案 0 :(得分:2)

您可以完全按照描述使用强制执行

  • 添加

    use Moose::Util::TypeConstraints;
    

    FirstSecond::Type1Second::Type2

  • Second::Type1

    添加强制操作
    coerce 'Second::Type1'
        => from 'Str'
            => via { Second::Type1->new( name => $_ ) };
    

    Second::Type2

    coerce 'Second::Type2'
        => from 'Str'
            => via { Second::Type2->new( name => $_ ) };
    
  • type1

    type2First属性启用强制
    has 'type1' => (
      is      => 'rw',
      isa     => 'Second::Type1',
      default => sub { Second::Type1->new },
      coerce  => 1,
    );
    
    has 'type2' => (
      is      => 'rw',
      isa     => 'Second::Type2',
      default => sub { Second::Type2->new },
      coerce  => 1,
    );
    

然后,您可以使用

完全按照您的说法创建First对象
my $first = First->new(type1 => 'foo', type2 => 'bar');

答案 1 :(得分:1)

你绝对可以用类型和强制来做。尝试使用http://orion.lab.fi-ware.org:1026/ngsi10/queryContext?limit=200&offset=0&details=off代替内置的。{/ p>

这是一个小例子,部分取自MooseX :: Types文档。

package Foo;
use Moose;
use MooseX::Types -declare => [qw(MyDateTime)];
use MooseX::Types::Moose 'Int';
use DateTime;

class_type MyDateTime, { class => 'DateTime' };
coerce MyDateTime, from Int, via { DateTime->from_epoch( epoch => $_ ) };

has date => (
    is      => 'ro',
    isa     => MyDateTime,
    default => sub {time},
    coerce  => 1,
);

package main;

my $foo = Foo->new;
say 'without args: ', $foo->date;

my $bar = Foo->new( date => time - 24 * 3600 );
say 'with args:    ', $bar->date;

这将打印如下内容:

without args: 2015-06-26T13:35:38
with args:    2015-06-25T13:35:38

它看起来很像你拥有的,只是使用更新的类型的东西。试一试。