如何创建一个新的 Moose 类并在运行时实例化该类的对象?

发布于 2024-08-24 17:43:27 字数 110 浏览 5 评论 0原文

使用 Moose::Meta::Class->create 创建元类后,如何使用该类作为元类实例化真正的 Moose 类? (我还需要创建元类,因为我还想对其应用一些角色。)

After creating a metaclass using Moose::Meta::Class->create, how do I instantiate a real Moose class with that class as a metaclass?
(I need to create the metaclass also because I also want to apply some roles to it.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

屋顶上的小猫咪 2024-08-31 17:43:27

当然,元类就是类。如果您想要该类的实例,只需执行以下操作:

my $instance = $meta->name->new

您可能还需要确保 $meta 不会过早被收集。一般来说,您会这样做:

$meta->add_method( meta => sub { $meta } );

这将保留元类,但如果您不小心,就会泄漏该类。如果你只做一次,那没关系;如果你这样做数千次,你可能会给自己带来麻烦。

最好使用更高级别的东西,例如 Moose::Meta::Class::create_anon_classMooseX::Traits

The metaclass is the class, of course. If you want an instance of that class, just do:

my $instance = $meta->name->new

You might also need to make sure that $meta doesn't get collected too soon. Generally, you do this:

$meta->add_method( meta => sub { $meta } );

That will keep the metaclass around, but you're going to leak the class if you aren't careful. If you only do this once, it won't matter; if you do it thousands of times, you could get yourself into trouble.

Much better to use something higher-level like Moose::Meta::Class::create_anon_class or MooseX::Traits.

高速公鹿 2024-08-31 17:43:27

不确定这是否回答了这个问题或您的其他问题如何在运行时构建 Moose 类,向其添加方法,向其应用角色并实例化一次?您将如何解决这个问题?位于构建驼鹿在运行时调用类并对其进行调整,但请查看:

它可能会做你想做的事。或者您可能会发现深入了解我们的工作原理很有用。

该文档确实提供了我在构建此模块时所做的博客文章的链接,因此您可能会发现这些文章也很有帮助。

以下是 MooseX::SingletonMethod 的简短代码示例:

{
    package Foo;
    use MooseX::SingletonMethod;
    sub bar { say 'bar' }
}

my $baz = Foo->new;
my $bar = Foo->new;

$baz->add_singleton_method( baz => sub { say 'baz' } );

$baz->bar;   # => bar
$bar->bar;   # => bar

$baz->baz;   # => baz
$bar->baz;   # Throws can't find baz error

/I3az/

Not sure this answers this or your other SO question How do I build a Moose class at runtime, add a method to it, apply a role to it and instantiate it once? How would you approach this? at Building a Moose class at runtime and tuning it but have a look at:

It may do what you want. Or you may find it useful to peer into our it works.

The documentation does provide links to blog posts I made while coming to grips with building this module so you may find those helpful also.

Here is an brief code example of MooseX::SingletonMethod:

{
    package Foo;
    use MooseX::SingletonMethod;
    sub bar { say 'bar' }
}

my $baz = Foo->new;
my $bar = Foo->new;

$baz->add_singleton_method( baz => sub { say 'baz' } );

$baz->bar;   # => bar
$bar->bar;   # => bar

$baz->baz;   # => baz
$bar->baz;   # Throws can't find baz error

/I3az/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文