perl - 驼鹿对象中的构建器子例程的参数

标签 perl moose

我目前正在将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/

相关文章:

perl - 在后台执行,但限制执行次数

arrays - 为什么 Perl 中的连接打印数组的 COUNT 而不是数组本身

perl - 为什么 MooseX::Storage 似乎没有遵循某些对象的属性特征?

perl - 如何在 Moose 构造函数中检查所需参数的有效性?

perl - 除了Catalyst之外,是否还有任何其他现代(Moose/PSGI)Web框架?

perl - 在 Perl 中隐藏来自用户的领带调用

windows - 如何调用传递给被调用程序的 VAR=$VAL 的系统?

从 C 调用 Perl 函数会导致崩溃

perl - 访问要在外部显式调用的包中的 Moose 对象

perl - 如何将 "lazy load"包用作委托(delegate)?