使用 Moose 在多态情况下对对象进行编码,其中客户端希望访问 $object->{private_variable} 数据

发布于 2024-12-05 12:51:20 字数 398 浏览 1 评论 0原文

我知道虽然 Moose 对象的内部表示(正确地)未定义。然而,在几乎所有情况下,它将是一个基本的受祝福的哈希引用。在创建新对象的情况下,该对象可能会被旧代码调用,该旧代码希望通过从受祝福的散列中获取对象属性来访问对象属性 ($object->{attribute}),而不是通过方法调用($object->attribute())封装到对象中,是否有任何方法可以显式定义该对象需要存储为祝福的哈希引用,以便属性工作正常吗?

更好的是,是否有任何模块可以将传递的受祝福的对象与对象内部表示解耦?似乎可以传递一个绑定哈希,该哈希可以将设置定义的哈希键绑定到针对实例化元对象的方法调用中,因此即使某些旧代码将该对象调用为 $object,所有类型检查仍然可以完成->{属性} = 'blahblah'。

I know that while the internal representation of a Moose object is (rightfully) left undefined. However, in almost all cases, it's going to be a basic blessed hashref. In a situation where a new object is being created that may be called by legacy code that expects to access object attributes by grabbing it from the blessed hash ($object->{attribute}) as opposed to being encapsulated into the object by a method call ($object->attribute()), is there any way to explicitly define that the object needs to be stored as a blessed hashref in order for attributes to work properly?

Even better, are there any modules out there that decouple the blessed object being passed around from the object internal representation? It seems like it'd be possible to pass a tied hash around that could tie set defined hash keys into method calls against the instantiated metaobject so all the type checking still gets done even if some old code calls the object as $object->{attribute} = 'blahblah'.

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

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

发布评论

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

评论(1

無心 2024-12-12 12:51:20
BEGIN {
    package MyMyMy;
    use Moose;
    has "watusi" =>
        is => "rw",
        isa => "Str";
}

my $mymymy = MyMyMy->new( watusi => "batusi" );
print $mymymy->watusi, $/;

$mymymy->watusi("woo-woo");
print $mymymy->{watusi}, $/;

$mymymy->{watusi} = "BAD DEV, BAD!";
print $mymymy->watusi, $/;

__END__    
batusi
woo-woo
BAD DEV, BAD!

我猜你已经知道这会是这样的。我发现很难想象 Moose 会以一种阻止其工作的方式改变内部结构。因此,尽管您试图做到正确,但如果您的真正目标只是从转储中获取一些遗留代码,我想说您可以依赖于此,前提是有一个真正的计划来前进并迁移到更多现代实践并防止界面违规。

BEGIN {
    package MyMyMy;
    use Moose;
    has "watusi" =>
        is => "rw",
        isa => "Str";
}

my $mymymy = MyMyMy->new( watusi => "batusi" );
print $mymymy->watusi, $/;

$mymymy->watusi("woo-woo");
print $mymymy->{watusi}, $/;

$mymymy->{watusi} = "BAD DEV, BAD!";
print $mymymy->watusi, $/;

__END__    
batusi
woo-woo
BAD DEV, BAD!

I’m guessing you already knew that would work the way it does. I find it extremely difficult to imagine that Moose will ever change the internals in a way that would prevent that from working. So, as correct as you’re trying to be, if your real aim is just to get some legacy code out of the dump, I’d say you could rely on this provided there is a real plan to move forward and migrate to more modern practices and prevent the interface violations.

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