简体   繁体   English

如何声明一个类在MooseX :: Declare中使用多个角色?

[英]How do I declare that a class uses more than one role with MooseX::Declare?

Given that the roles Fooable and Barable have both been defined, how do I say that class FooBar does Fooable and Barable? 鉴于角色Fooable和Barable都已定义,我怎么说FooBar类可以做Fooable和Barable? I have no problem saying 我没问题

#!/usr/bin/perl

use MooseX::Declare;

role Fooable {
    method foo { print "foo\n" }
}

role Barable {
    method bar { print "bar\n" }
}

class Foo with Fooable {}
class Bar with Barable {}

package main;

use strict;
use warnings;

Foo->new->foo;
Bar->new->bar;

But when I try to add 但是当我尝试添加时

class FooBar with Fooable, Barable {}

I get the less than useful error 我得到的不是有用的错误

expected option name at [path to MooseX/Declare/Syntax/NamespaceHandling.pm] line 45

Just to prove to myself that I am not crazy, I rewrote it using Moose. 为了向自己证明我并不疯狂,我用Moose重写了它。 This code works (but is uglier than sin): 这段代码有效(但比罪恶更丑):

#!/usr/bin/perl

package Fooable;
    use Moose::Role;    
    sub foo { print "foo\n" }

package Barable;    
    use Moose::Role;    
    sub bar { print "bar\n" }

package Foo;    
    use Moose;    
    with "Fooable";

package Bar;    
    use Moose;    
    with "Barable";

package FooBar;    
    use Moose;    
    with "Fooable", "Barable";

package main;

use strict;
use warnings;

Foo->new->foo;
Bar->new->bar;
FooBar->new->foo;
FooBar->new->bar;

Apparently you need parentheses: 显然你需要括号:

#!/usr/bin/perl

use MooseX::Declare;

role Fooable {
    method foo { print "foo\n" }
}

role Barable {
    method bar { print "bar\n" }
}

class Foo with Fooable {}
class Bar with Barable {}
class FooBar with (Fooable, Barable) {}

package main;

use strict;
use warnings;

Foo->new->foo;
Bar->new->bar;
FooBar->new->foo;
FooBar->new->bar;

Just to note that this also works: 请注意,这也有效:

class FooBar with Fooable with Barable {}

This seems the most common usage I've seen in MooseX::Declare world. 这似乎是我在MooseX :: Declare world中看到的最常见的用法。

Also note you can use the "classic" way also: 另请注意,您还可以使用“经典”方式:

class FooBar {
    with qw(Fooable Barable);
}

There are cases where this is needed because this composes the role immediately whereas defining role in the class line gets delayed till the end of the class block. 在某些情况下需要这样做,因为它会立即组成角色,而在类行中定义角色会延迟到类块结束。

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

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