如何通过 MooseX::Declare 声明一个类使用多个角色?
鉴于 Fooable 和 Barable 角色都已定义,那么如何说 FooBar 类负责 Fooable 和 Barable 呢? 我没有问题说
#!/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;
但是当我尝试添加时
class FooBar with Fooable, Barable {}
我得到了不太有用的错误
expected option name at [path to MooseX/Declare/Syntax/NamespaceHandling.pm] line 45
只是为了向自己证明我没有疯,我用 Moose 重写了它。 这段代码有效(但比罪恶更丑陋):
#!/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;
Given that the roles Fooable and Barable have both been defined, how do I say that class FooBar does Fooable and 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. 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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显然你需要括号:
Apparently you need parentheses:
请注意,这也有效:
这似乎是我在 MooseX::Declare world 中看到的最常见用法。
另请注意,您也可以使用“经典”方式:
在某些情况下需要这样做,因为这会立即组成角色,而在类行中定义角色会延迟到类块的末尾。
Just to note that this also works:
This seems the most common usage I've seen in MooseX::Declare world.
Also note you can use the "classic" way also:
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.