In Perl/Moose, how can I apply a modifier to a method in all subclasses?

喜夏-厌秋 提交于 2019-12-22 03:48:13

问题


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"
}

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.


回答1:


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.



来源:https://stackoverflow.com/questions/4965197/in-perl-moose-how-can-i-apply-a-modifier-to-a-method-in-all-subclasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!