我目前正在将构建器方法委托给扩展我的一个基类的所有对象.我面临的问题是我需要所有对象来读取自身的属性或传递一个值.
# 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?
}
Run Code Online (Sandbox Code Playgroud)
这是目前可能的还是我将不得不以其他方式做到这一点?
Eth*_*her 12
您不能将参数传递给属性构建方法.它们由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');
Run Code Online (Sandbox Code Playgroud)
另请注意,如果您具有基于其他属性值构建的属性,则应将其定义为lazy,否则构建器/默认值将立即在对象构造上运行,并且以未定义的顺序运行.将它们设置为懒惰将延迟它们的定义,直到它们首次需要为止.
| 归档时间: |
|
| 查看次数: |
2210 次 |
| 最近记录: |