Created
May 20, 2010 22:52
-
-
Save isterin/408224 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use Scalar::Util qw(weaken refaddr); | |
my $c = Test->load("child"); | |
my $test; | |
{ | |
my $p = Test->load("parent"); | |
$test = $p; | |
weaken($test); | |
$c->set_parent($p); | |
warn("Child addr: ".sprintf("%x", refaddr(\$c)).", test ref addr: ".sprintf("%x", refaddr(\$test))."\n"); | |
$p->set_child($c); | |
} | |
warn("Destroy of parent should have been called before this point."); | |
####################### packages below ########################## | |
package ProxyStub; | |
use Scalar::Util qw(weaken); | |
sub new { | |
my $class = shift; | |
my $obj_instance = shift; | |
my $self = { | |
__instance => $obj_instance, | |
__instance_id => $obj_instance->get_id(), | |
__instance_class => ref $obj_instance | |
}; | |
weaken($self->{__instance}); | |
return bless $self, $class; | |
} | |
sub _get_instance { | |
my ($self) = shift; | |
unless ($self->{__instance}) { | |
warn("Instance is garbage collected, loading... [". | |
$self->{__instance_class}."->load(" . $self->{__instance_id} . ")]\n"); | |
$self->{__instance} = $self->{__instance_class}->load($self->{__instance_id}); | |
} | |
return $self->{__instance}; | |
} | |
sub AUTOLOAD { | |
my $self = shift; | |
my $method = $AUTOLOAD; | |
$method =~ s/.*:://; | |
warn("Proxying: $method\n"); | |
$self->_get_instance()->$method(@_); | |
} | |
package Test; | |
use Scalar::Util qw(weaken); | |
use Devel::Peek; | |
sub load { | |
my ($class, $id) = @_; | |
warn("Loading $class as $id"); | |
return bless {__id => $id}, $class; | |
} | |
sub set_parent { | |
my ($self, $p) = @_; | |
$self->{__parent} = $p; | |
weaken($self->{__parent}); | |
# warn("Weak ref addr: " . refaddr($self)); | |
} | |
sub get_parent { | |
my ($self) = @_; | |
return $self->{__parent}; | |
} | |
sub set_child { | |
my ($self, $c) = @_; | |
$self->{__child} = $c; | |
} | |
sub get_id { | |
return shift->{__id}; | |
} | |
sub DESTROY { | |
my $self = shift; | |
warn("Destroying: " . ref($self) . ", " . $self->get_id()); | |
## Here, I'd love to swap any weak references to this object with a proxy??? | |
Dump($self); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment