moose 对象中构建器子例程的参数
我目前正在将构建器方法委托给扩展我的基类之一的所有对象。我面临的问题是我需要所有对象读取其自身的属性或传递一个值。
# 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?
}
目前这可能吗,还是我必须采取其他方式?
I'm currently delegating the builder method to all of the objects that extend one of my base classes. The problem that I'm facing is I need all of the objects to either read an attribute of itself or be passed in a value.
# 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?
}
Is this currently possible or am I going to have to do it some other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法将参数传递给属性构建方法。它们由 Moose 内部结构自动调用,并且只传递一个参数——对象引用本身。构建器必须能够根据它在
$self
中看到的内容或它有权访问的环境中的任何其他内容返回其值。您想向构建者传递什么样的论点?您可以将这些值传递给对象构造函数并将它们存储在其他属性中吗?
另请注意,如果您有基于其他属性值构建的属性,则应将它们定义为惰性,否则构建器/默认值将在对象构造时立即运行,并且以未定义的顺序运行。将它们设置为惰性会延迟它们的定义,直到第一次需要它们为止。
You can't pass arguments to attribute build methods. They are called automatically by Moose internals, and passed only one argument -- the object reference itself. The builder must be able to return its value based on what it sees in
$self
, or anything else in the environment that it has access to.What sort of arguments would you be wanting to pass to the builder? Can you instead pass these values to the object constructor and store them in other attributes?
Also note that if you have attributes that are built based off of other attribute values, you should define them as
lazy
, otherwise the builders/defaults will run immediately on object construction, and in an undefined order. Setting them lazy will delay their definition until they are first needed.你可以这样做:
You can do something like this: