使用 Moose 在多态情况下对对象进行编码,其中客户端希望访问 $object->{private_variable} 数据
我知道虽然 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜你已经知道这会是这样的。我发现很难想象 Moose 会以一种阻止其工作的方式改变内部结构。因此,尽管您试图做到正确,但如果您的真正目标只是从转储中获取一些遗留代码,我想说您可以依赖于此,前提是有一个真正的计划来前进并迁移到更多现代实践并防止界面违规。
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.