在Perl / Moose中,如何将修改器应用于所有子类中的方法? [英] In Perl/Moose, how can I apply a modifier to a method in all subclasses?
问题描述
我有一个Moose类,它打算被子类化,每个子类都必须实现一个execute方法。但是,我想将一个方法修饰符应用于我的类中的execute方法,以便它适用于所有子类中的execute方法。但是当方法被覆盖时,方法修饰符不会被保留。有没有办法确保我的类的所有子类都将我的方法修饰符应用于它们的执行方法?
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?
示例:在超类中,我有:
Example: In a superclass, I have this:
before execute => sub {
print "Before modifier is executing.\n"
}
然后,在其子类中:
sub execute {
print "Execute method is running.\n"
}
当调用execute方法时,它没有说明任何关于之前修饰符。
When the execute method is called, it doesn't say anything about the "before" modifier.
推荐答案
这就是 augment
方法修饰符是为了。你可以把它放在你的超类中:
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.
这篇关于在Perl / Moose中,如何将修改器应用于所有子类中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!