开发者

Using Moose to code objects in a polymorphic situation where clients expect to access $object->{private_variable} data

开发者 https://www.devze.com 2023-04-05 16:27 出处:网络
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 obje

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 the开发者_开发知识库re 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'.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号