我目前正在将builder方法委派给扩展我的基类之一的所有对象。我面临的问题是我需要所有对象读取其自身的属性或将其传递给值。
# In Role:
has 'const_string' => (
isa => 'Str',
is => 'ro',
default => 'test',
);
has 'attr' => (
isa => 'Str',
is => 'ro',
builder => '_builder',
);
requires '_builder';
# In extending object - desired 1
sub _builder {
my ($self) = shift;
# $self contains $self->const_string
}
# In extending object - desired 2
sub _builder {
my ($arg1, $arg2) = @_;
# $args can be passed somehow?
}
这目前可能吗?还是我需要以其他方式来做到这一点?
最佳答案
您不能将参数传递给属性构建方法。它们由Moose内部自动调用,并且仅传递一个参数-对象引用本身。构建器必须能够根据它在$self
或它可以访问的环境中的任何其他内容返回的值。
您想传递给构建器什么样的参数?您可以改为将这些值传递给对象构造函数并将它们存储在其他属性中吗?
# in object #2:
has other_attr_a => (
is => 'ro', isa => 'Str',
);
has other_attr_b => (
is => 'ro', isa => 'Str',
);
sub _builder
{
my $self = shift;
# calculates something based on other_attr_a and other_attr_b
}
# object #2 is constructed as:
my $obj = Class2->new(other_attr_a => 'value', other_attr_b => 'value');
还要注意,如果您具有基于其他属性值构建的属性,则应将它们定义为
lazy
,否则生成器/默认值将在对象构造上立即运行,并且顺序未定义。将它们设置为惰性将延迟其定义,直到首次需要它们时为止。
关于perl - 驼鹿对象中的构建器子例程的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3291100/