0

是否可以在 Role 中使用 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 { ... }
4

1 回答 1

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;
}
于 2013-02-18T17:03:57.260 回答