In general, I like your approach - a lot.

One thing that annoyed me is the $self->self meme. Confusing, IMO, and not efficient either. I toyed around with the idea of wrapping subs in some way, but haven't come up with any really consistent and watertight semantics. :-/ The only possibility would be to tie all field hashes to a class that autocasts any refs used as keys into their refaddr before using them but that doesn't perform any better. Overloading the stringification on the reference might help, but will neither perform better nor work reliably if someone else overloads the same operation. So there really seems to be no other way than to remind everyone to use $self->self everywhere. Though I'd probably call that $self->_id instead. Or maybe an attribute Self? Not sure yet.. gonna have to look into that.

That aside, here's my take on the base class - minus refaddr cause it doesn't work on 5.6.1. What I do is quite simple: store the hashref to the pad :-). Then all that AUTOLOAD has to do is trawl through the pad hashrefs and look for a matching attribute.

#!/usr/bin/perl use strict; use warnings; package Class::InsideOut; use NEXT; use Attribute::Handlers; use PadWalker qw(peek_my); use Data::Dumper; use vars qw($AUTOLOAD); my (@Field, %Pad); sub Field : ATTR(HASH) { my ($class, $symbol, $hash) = @_; push @Field, $hash; my $pad = peek_my(3); $Pad{$class}->{$pad} = peek_my(3); } sub AUTOLOAD { my $self = $_[0]; my ($class, $field) = $AUTOLOAD =~ /^(.*)::(.*)$/; $field = "%".$field; my @field = grep exists $_->{$field}, values %{$Pad{$class}}; if(@field) { $field = $field[0]; no strict 'refs'; *{$AUTOLOAD} = sub { my $self = shift; @_ ? $field->{$self} = shift : $field->{$self}; }; goto &{$AUTOLOAD}; } else { warn "\@field is empty"; return $self->NEXT::AUTOLOAD; } } sub DESTROY { my $self = $_[0]; delete $_->{$self} for @Field; $self->NEXT::DESTROY() } 1;
And some test code:
package Foo::Bar; use base qw(Class::InsideOut); use Data::Dumper; my (%foo, %bar, %baz): Field; package main; my $x = bless [], 'Foo::Bar'; $x->foo("bar!\n"); print $x->foo(), "\n"; __END__ bar!
I don't know if it's watertight, though. In particular, how well will it work if I call an accessor for a superclasses' field on a subclass?

Makeshifts last the longest.


In reply to Re: Class::InsideOut - yet another riff on inside out objects. by Aristotle
in thread Class::InsideOut - yet another riff on inside out objects. by adrianh

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":