overload proxy object



I have occasional objects that are heavy to instantiate. Because of the way the application is structured, often these objects won't even be used (they are available if needed but they may not be needed). So to reduce the resources of this application I have surrounded these objects with a proxy object that delays instantiation.

Basically when the object is created you create it like this:

my $curusr = new Class::Delayed(sub {new Data::User($uid)})

Data::User is heavy because it does some database queries to get it's attributes. But often the code doesn't even use $curusr meaning those queries were for nothing. Now the proxy object looks like this:

******* BEGIN CLASS **********

package Class::Delayed;

sub new {
	my ( $class, $closure ) = @_;
	my $self = {};
	bless( $self, $class );
	$self->{closure} = $closure;
	return $self;
}

sub AUTOLOAD {
	my ( $self, @args ) = @_;
	$AUTOLOAD =~ s/.*:://;
	return if !exists($self->{obj}) and $AUTOLOAD eq 'DESTROY';
	$self->{obj} = $self->{closure}->() unless exists $self->{obj};
	$self->{obj}->$AUTOLOAD(@args);
}

1;

*********** END CLASS **********

As you can see anytime any method is called on the object it will instantiate the object if it was not already created. It creates the object by calling the closure that was passed into the proxy object.

This all works real well except when the real object is using overloads. Many of the objects have "", cmp and <=> overloads (for sorting and printing) and these no longer work. I am guessing because my overload methods do not pass through AUTOLOAD.

I think I might be able to use the "nomethod" overload but it looks like my implementation of nomethod will need to look at the symbol and then carry out the operation according to each symbol. This seemed like a bit of work (not too much but a bit) so I think maybe there is a better more simpler way to just say "all overloads for object X get passed to object Y". Any ideas?

Eric
.