简体   繁体   English

驼鹿属性-接受具有共同父代的多个模块

[英]Moose attributes - accepting multiple modules with common parent

Need do something like the next (and more): 需要做类似下一个(和更多)的事情:

my $val1 = My::Module::Type1->new(...);
my $val2 = My::Module::Type2->new(...);

my $some = Some->new( val => [$val1, $val2] );

How to define the $val in a Some package (Moose based)? 如何在Some包(基于Moose)中定义$val So, 所以,

package Some;
use Moose;
has 'val' => (
    isa => 'ArrayRef[My::Module::__ANYTHING__HERE__]', # <-- here is the problem
);

The problem is than now have only My::Module::Type1 but how to construct the Some->val for accepting any future My::Module::_something_ ? 现在的问题是只有My::Module::Type1但是如何构造Some->val来接受任何将来的My::Module::_something_吗?

My best idea is 我最好的主意是

use Moose;
use Moose::Util::TypeConstraints;
usa Scalar::Util qw( blessed );

subtype MySubModule,
    as Object => where {
         blessed $_ =~ /^My::Module/
    },
    message { "Need My::Module class" };

has val => ( is => 'rw', isa => 'ArrayRef[MySubModule]' );

But i don't think than this is a best way, because what if someone makes Your::Module what will be a subclass of My::Module ? 但是我认为这不是最好的方法,因为如果有人将Your::Module变成My::Module的子类,该怎么办?

Can anybody advice me something more correct solution? 有人可以建议我一些更正确的解决方案吗?

(Probably will need somewhat incorporate roles, (or traits), but (honestly) - still never used any Role - and haven't idea how to use them.. ;( ) (可能需要在某种程度上包含角色(或特质),但是(诚实地)-仍然从未使用过任何角色-并且不知道如何使用它们。

I hope the above is understandable - unfortunately my english is similary bad as my perl.. ;( 我希望以上内容是可以理解的-不幸的是,我的英语和我的英语相似。.;

Use a class type constraint. 使用类类型约束。 It respects inheritance... 它尊重继承...

use Moose;
use Moose::Util::TypeConstraints;

class_type 'MyModule', { class => 'My::Module' };

has val => ( is => 'rw', isa => 'ArrayRef[MyModule]' );

Or better (though bear in mind I'm biased)... 或者更好(尽管请记住我有偏见)...

use Moose;
use Types::Standard -types;

has val => (is => 'rw', isa => ArrayRef[InstanceOf['My::Module']]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM