如何将非 OO 函数模块包装到 moose 类中
几个月前我开始使用 Moose。
我使用一些非 OO 模块,它们只是由相关函数组成。我想在 Moose 类中使用这些函数作为方法。可能是最简单的方法,就像
#!/usr/bin/env perl
package FuncPack;
sub func_1 {
print "-> ", __PACKAGE__, "::func_1 called \n";
}
package FuncClass;
use Moose;
use namespace::autoclean;
sub func_1 {
my $self = shift ;
return FuncPack::func_1(@_);
}
__PACKAGE__->meta->make_immutable;
package main;
my $obj = FuncClass->new();
$obj->func_1(); # shall call FuncPack::func_1
对于一个功能来说可能没问题,但如果你有很多功能,那就是一项重复的任务并且很无聊。 有没有更聪明的方法来实现它?可能有类似于 MooseX::NonMoose 或 MooseX::InsideOut 的东西用于扩展非 Moose 类?
感谢您的建议或提示。
A few month ago I started to use Moose.
There are some non-OO modules I use simply made of related functions. I'd like to use these functions in Moose classes as methods. May be the simplest way doing it is like
#!/usr/bin/env perl
package FuncPack;
sub func_1 {
print "-> ", __PACKAGE__, "::func_1 called \n";
}
package FuncClass;
use Moose;
use namespace::autoclean;
sub func_1 {
my $self = shift ;
return FuncPack::func_1(@_);
}
__PACKAGE__->meta->make_immutable;
package main;
my $obj = FuncClass->new();
$obj->func_1(); # shall call FuncPack::func_1
For one function it may be ok, but if you have a lot it's a repeating task and boring.
Is there a more clever way to accomplish it ? May be there is something similar to MooseX::NonMoose or MooseX::InsideOut which are for extending non-Moose classes ?
Thanks for advice or hints.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Moose 通常不处理这个问题,将非 OO 模块包装在 OO 框架中似乎有点奇怪。但是,如果您有一个方法列表(或可以生成一个方法),您可以执行以下操作:
您可以使用诸如
Package::Stash
之类的方法从中提取函数列表>FuncPack
。但我想知道你为什么要这样做?您的
FuncClass
将绝对不携带任何状态,并且除了添加间接层之外实际上没有任何其他用途。Moose typically doesn't deal with this, wrapping non-OO modules in an OO framework seems a bit odd. However if you have a list of the methods (or can generate one) you could do something like:
You may be able to use something like
Package::Stash
to pull out the list of functions fromFuncPack
.I'm wondering however why you would want to do this to begin with? Your
FuncClass
will be carrying absolutely no state, and really doesn't serve a purpose other than to add a layer of indirection.