簡體   English   中英

修改Moose屬性方法

[英]Modify Moose attribute methods

我正在創建一個屬性列表(比下面顯示的三個要多),所有這些屬性共享通用方法。 然后可以向其中一種方法添加觸發器:

# Create a bunch of attributes
for my $attr ( qw( title name address ) ) {
    has $attr => ( is => 'rw', isa => 'Str' );

    around $attr => sub {
        # more stuff here.
    }
}

# Add a trigger
has_another_method 'title' => ( trigger => \&_trigger_title );

我知道我可以獲取有關屬性的元信息,但是我還沒有發現任何能使我更改屬性方法的信息(也許有充分的理由)。 能夠做到這一點將有助於保持我的代碼整潔,並意味着所有公共位都在一個位置定義。 如果沒有,我可以單獨創建屬性,並包含觸發方法。

更新

答案清楚地表明,在創建屬性后更改屬性不是一個好主意。 相反,我選擇了一種不同的方法,該方法使我可以將所有屬性選項都放在一個位置。 這個例子有點簡單,但是它說明了這個想法:

# Create a bunch of attributes
for my $attr ( qw( title name address ) ) {

    my %options = ( is => 'rw', isa => 'Str' );

    # Add a trigger to the title attribute.
    $options{ 'trigger' } = \&_trigger_title
        if $attr eq 'title';

    has $attr => ( %options );

    around $attr => sub {
        # more stuff here.
    }
}

觸發器只是該屬性上的一個屬性,但是它們被定義為只讀。 可以 find_meta( $attribute )->get_attribute('trigger')->set_value( $attribute, sub { new trigger }) ,但實際上是在破壞封裝。

我只是在for循環中聲明所有通用屬性,然后在其他地方聲明特殊情況。

屬性方法是在構造它們時組成的,因此通常最好的做法是在使用has指令創建屬性時使用所有選項。 但是 ,當前觸發器方法沒有做任何特別的事情,因此您可以這樣做,以解決“ trigger”選項的只讀性:

my $attr = __PACKAGE__->meta->get_attribute('title')->meta->get_attribute('trigger')->set_raw_value('_trigger_sub_name');

但是,這相當地深入了Moose的內部。 如果實現發生變化,您可以是SOL(加上您會因為某種原因違反那里的約束)。 因此,這將是更好的來設置觸發器為:

has $_ => (
    is => 'rw', isa => 'Str',
    trigger => '_trigger_' . $_,
) for (qw(title name address));

sub _trigger_title {
    # implementation here
}
sub _trigger_name {
    # implementation here
}
sub _trigger_address {
    # implementation here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM