可以在角色中使用after修饰符,以通过构建器方法在使用类中填充所需的属性吗?
package A::Role;
use Moose::Role;
use IO::File;
use Carp;
requires 'properties_file';
after 'properties_file' => sub {
my $self = shift;
$self->_check_prop_file();
$self->_read_file();
};
消费类:
package A::B::C;
use Moose;
use Carp;
use Moose;
use Carp;
use HA::Connection::SSH;
use constant {
...
};
has 'properties_file' => ( is => 'ro',
isa => 'Str',
builder => '_build_current_data');
with 'A::Role';
sub _build_current_data { ... }
答案 0 :(得分:0)
回答你的问题:是的,你可以。您已经完成了在声明属性后使用角色以便生成访问器方法的关键部分。
因此,您提供的代码将按照您期望的顺序执行: -
my $c = A::B::C->new;
# 'properties_file' is built by _build_current_data()
my $filename = $c->properties_file;
# _check_prop_file() and _read_file() are executed (but before $filename is assigned)
但是,通过获取 properties_file
来调用和读取属性文件似乎很奇怪。如果您只想在构造后自动检查和读取属性文件,则该角色可以提供要在类中使用的BUILD
方法。 (BUILD
在构造后执行,因此properties_file
将初始化。)
sub BUILD {
my $self = shift;
$self->_check_prop_file();
$self->_read_file();
return;
}