Last active
August 29, 2015 14:07
-
-
Save XoseLluis/d2295294114375fa7913 to your computer and use it in GitHub Desktop.
Basic Proxy example in Perl using AUTOLOAD
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
#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; |
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
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; |
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
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