Moose::Role - 增强角色应用的简单方法?
我有一个 Moose::Role
,当该角色应用于该类时,我想在该类上调用一些额外的子函数。
有没有一种简单的方法可以修改应用角色时发生的情况,而不必深入研究 Moose::Meta::Role
类型编码?理想情况下,我只想在“apply”=>之后...
添加额外的东西。
编辑:
我专门将其与 DBIx::Class::Core
结果定义一起使用,以创建类似也修改构造函数的组件之类的内容。如果我可以得到 BUILDARGS
和 BUILD
子结果,我会把它写成一个组件,但我似乎做不到。因此,我没有执行 load_component
,而是执行 with 'role'
,但组件的一些效果是将 belongs_to
关系添加到班级。因此,我认为最好的方法是将角色应用到课堂上。
I have a Moose::Role
that I would like to call some extra subs on the class when that role is applied to the class.
Is there an easy way to modify what happens when the role is applied, without having to dig too much into Moose::Meta::Role
type coding? Ideally, I'd just like to after 'apply' => ...
to add the extra stuff.
Edit:
I'm specifically using this with a DBIx::Class::Core
result definition to create something like a component that also modifies the constructor. I would just write it as a component if I could get at BUILDARGS
and BUILD
subs for the result, but I can't seem to do. So, instead of doing load_component
, I doing with 'role'
, but some of the effects of the component are to add belongs_to
relationships to the class. Hence, I was thinking the best way to do that is during application of the role to the class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在简短的评论中,我向您推荐了 这个问题,它讨论如何访问角色所应用的类的元类(例如,以便您可以有条件地构建该类)。然而,使用 MooseX::Role::Parameterized 为您提供该信息确实很糟糕,而且如果将角色应用于另一个角色而不是类,它也将不起作用。
作为替代方案,您可以编写一个接收元信息的糖函数,并以这种方式构建到类上:
请参阅 Moose::Cookbook::Extending::Recipe4 了解编写糖函数的示例。
In a briefly-lived comment I referred you to this question, which discusses how to access the metaclass of the class the role is being applied to (e.g. so you can build onto the class conditionally). However, that's a really stinky use of MooseX::Role::Parameterized providing you that information, and it also won't work if the role is being applied to another role, not to a class.
As an alternative, you could write a sugar function which receives the meta information, and build onto the class in that way:
See Moose::Cookbook::Extending::Recipe4 for an example of writing sugar functions.
您可以使用参数化角色。 教程。话虽这么说,我建议您加入 Moose 和 DBIx-Class IRC 频道或邮件列表,以寻找这方面的最佳实践。
You could use a parameterized role. There is an example on how to access the consuming class in the tutorial. That being said, I would advise you to join the Moose and DBIx-Class IRC channels or mailing lists to look for best-practices in this regard.
我发现有效、紧凑并且似乎符合文档中的意图的是使用一个特征来修改我的特定角色使用的元角色:
What I found that works, is compact, and seems in keeping with intent in the docs is to use a trait to modify the meta role used by my particular role: