我正在尝试使用Mouse编写一个perl模块,并且在初始化对象之后,但在用户进行任何调用之前,我需要使用object2和object3中的两个值初始化object1用户被要求给予。我尝试使用Mouse的after
功能来调用new
之后的子程序:
package Test;
use strict;
use Mouse;
has 'object1' => ( is => 'rw', isa => 'Any');
has 'object2' => ( is => 'ro', isa => 'Str', required => 1);
has 'object3' => ( is => 'ro', isa => 'Str', required => 1);
after 'new' => sub {
my ($self) = @_;
$self->object1(#do stuff with object2 and object3);
};
1;
但是,目前我收到此错误:
Invalid object instance: 'Test' at lib/Test.pm line 18.
有没有办法在用户获取返回给它们的对象引用之前用用户提供的值初始化值?
答案 0 :(得分:2)
鼠标与Moose兼容。对象创建有以下几个阶段:
BUILDARGS
方法传递参数。这可以在Moose / Mouse触摸它们之前消除参数,例如提供默认参数或容纳除关键字约定之外的其他调用样式。has
声明)。BUILD
方法执行检查。在这一点上,您还可以执行无法用has
声明表达的剩余初始化。所以你的例子可能会成为:
use strict;
use warnings;
package Your::Class;
use Mouse;
has 'object1' => ( is => 'rw', isa => 'Any');
has 'object2' => ( is => 'ro', isa => 'Str', required => 1);
has 'object3' => ( is => 'ro', isa => 'Str', required => 1);
sub BUILD {
my ($self) = @_;
$self->object1($self->object2 . $self->object3);
};
package main;
use Test::More;
# Your::Class->new(object2 => "foo", object3 => "bar");
my $instance = new_ok('Your::Class', [object2 => "foo", object3 => "bar"]);
is($instance->object1, "foobar");
done_testing;
要了解有关Moose和Moose兼容对象系统中对象构造的更多信息,请阅读Moose::Manual::Construction
。