在Perl / Moose中,如何将修改器应用于所有子类中的方法?

时间:2022-03-06 21:04:26

I have a Moose class that is intended to be subclassed, and every subclass has to implement an "execute" method. However, I would like to put apply a method modifier to the execute method in my class, so that it applies to the execute method in all subclasses. But method modifiers are not preserved when a method is overriden. Is there any way to ensure that all subclasses of my class will have my method modifier applied to their execute methods?

我有一个Moose类,它打算被子类化,每个子类都必须实现一个“execute”方法。但是,我想将一个方法修饰符应用于我的类中的execute方法,以便它适用于所有子类中的execute方法。但是当方法被覆盖时,方法修饰符不会被保留。有没有办法确保我的类的所有子类都将我的方法修饰符应用于它们的执行方法?

Example: In a superclass, I have this:

示例:在超类中,我有:

before execute => sub {
    print "Before modifier is executing.\n"
}

Then, in a subclass of that:

然后,在其子类中:

sub execute {
    print "Execute method is running.\n"
}

When the execute method is called, it doesn't say anything about the "before" modifier.

调用execute方法时,它没有说明“before”修饰符。

1 个解决方案

#1


9  

This is what the augment method modifier is made for. You can put this in your superclass:

这就是增强方法修饰符的用途。你可以把它放在你的超类中:

sub execute {
  print "This runs before the subclass code";
  inner();
  print "This runs after the subclass code";
}

And then instead of allowing your subclasses to override execute directly, you have them augment it:

然后,不是让你的子类直接覆盖执行,而是让它们增加它:

augment 'execute' => sub {
  print "This is the subclass method";
};

Basically it gives you functionality that's just like the around modifier, except with the parent/child relationship changed.

基本上它给你的功能就像around修饰符一样,除了父/子关系改变了。

#1


9  

This is what the augment method modifier is made for. You can put this in your superclass:

这就是增强方法修饰符的用途。你可以把它放在你的超类中:

sub execute {
  print "This runs before the subclass code";
  inner();
  print "This runs after the subclass code";
}

And then instead of allowing your subclasses to override execute directly, you have them augment it:

然后,不是让你的子类直接覆盖执行,而是让它们增加它:

augment 'execute' => sub {
  print "This is the subclass method";
};

Basically it gives you functionality that's just like the around modifier, except with the parent/child relationship changed.

基本上它给你的功能就像around修饰符一样,除了父/子关系改变了。