在 Moose 构建器中使用子引用
Using sub reference with Moose builder
Moose 文档提到 builder
属性 for attribute in class definiton 应该是一个字符串,其中包含将被调用以构建相关属性的函数的名称。然而,简单的测试表明子引用也可以工作:
has 'some_attribute' => (
is => 'ro',
lazy => 1,
builder => sub {
require SomeModule::Heavy;
return SomeModule::Heavy->new($_[0]);
},
);
我是否遗漏了文档中的内容? builder
是否正式支持子引用的使用?
Moose manual 说:
You can also provide a subroutine reference for default
. This reference will be called as a method on the object. […] As an alternative to using a subroutine reference, you can supply a builder
method for your attribute. This has several advantages. First, it moves a chunk of code to its own named method, which improves readability and code organization. Second, because this is a named method, it can be subclassed or provided by a role.
因此,如果您对 builder
使用子例程引用,那么您将失去这些优势。我认为子例程引用是副作用,没有实际应用。
Moose 文档提到 builder
属性 for attribute in class definiton 应该是一个字符串,其中包含将被调用以构建相关属性的函数的名称。然而,简单的测试表明子引用也可以工作:
has 'some_attribute' => (
is => 'ro',
lazy => 1,
builder => sub {
require SomeModule::Heavy;
return SomeModule::Heavy->new($_[0]);
},
);
我是否遗漏了文档中的内容? builder
是否正式支持子引用的使用?
Moose manual 说:
You can also provide a subroutine reference for
default
. This reference will be called as a method on the object. […] As an alternative to using a subroutine reference, you can supply abuilder
method for your attribute. This has several advantages. First, it moves a chunk of code to its own named method, which improves readability and code organization. Second, because this is a named method, it can be subclassed or provided by a role.
因此,如果您对 builder
使用子例程引用,那么您将失去这些优势。我认为子例程引用是副作用,没有实际应用。