Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XoseLluis/d2295294114375fa7913 to your computer and use it in GitHub Desktop.
Save XoseLluis/d2295294114375fa7913 to your computer and use it in GitHub Desktop.
Basic Proxy example in Perl using AUTOLOAD
#http://deploytonenyures.blogspot.fr/2014/10/methodmissing.html
package AroundProxy;
use strict; use warnings;
sub New {
my ($class, $targetObj, $interceptorFunc) = @_;
my $self = {
targetObj => $targetObj,
interceptorFunc => $interceptorFunc
};
bless $self, $class;
return $self;
}
sub AUTOLOAD {
my $self = shift;
my $methodName = our $AUTOLOAD;
$methodName =~ s/.*:://;
#do not intercept calls to DESTROY (as most classes won't define it and we'll get a warning)
if($methodName eq 'DESTROY') {return;}
return $self->{interceptorFunc}->($methodName, $self->{targetObj}, @_);
}
1;
package Person;
use strict; use warnings;
sub New {
my $class = shift;
my $self = {
Name => shift
};
bless $self, $class;
return $self;
}
sub SayHi{
my $self = shift;
return $self->{Name} . " is saying Hi";
}
1;
package Test;
use strict; use warnings;
use Person;
use AroundProxy;
sub aroundTest{
print "". (caller(0))[3] . "\n";
my ($p1) = @_;
my $proxy = AroundProxy->New($p1,
sub{
my $methodName = shift;
my $targetObj = shift;
print "$methodName started with params:" . join(", ", @_) . "\n";
my $res = $targetObj->$methodName(@_);
print "$methodName finished\n";
return $res;
}
);
print $proxy->SayHi() . "\n";
}
my $p1 = Person->New("Iyan");
aroundTest($p1);
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment