If you want to delegate some methods to another object Class::Delegation can be of great help. For example if we have:
{ package Foo; sub new { bless {}, shift }; sub sane { 42 }; sub insane { 666 }; };
We can make a SaneFoo class that forwards calls to the sane method to an internal Foo object like this:
{ package SaneFoo; use Class::Delegation send => 'sane', to => 'Foo'; sub new { bless { Foo => Foo->new }, shift; }; };
Which does what we want:
use Test::More tests => 3; use Test::Exception 0.15; isa_ok my $o = SaneFoo->new, 'SaneFoo'; lives_and {is $o->sane, 42} 'sane worked'; dies_ok {$o->insane} 'insane failed'; __END__ # test results are: 1..3 ok 1 - The object isa SaneFoo ok 2 - sane worked ok 3 - insane failed
If you are worried about people burrowing into the SaneFoo object and extracting the Foo object from the hash you can always use Abigail-II's inside out objects. Using this style the SaneFoo class could be implemented like this:
{ package SaneFoo; use Carp; my %Foo = (); sub new { my $self = bless {}, shift; $Foo{$self} = Foo->new; return($self); }; sub allows { my ($self, $method) = @_; return( $method eq "sane" ); }; sub AUTOLOAD { my $self = shift; our $AUTOLOAD; my ($method) = ($AUTOLOAD =~ m/([^:]+)$/); croak "$self cannot $method" unless $self->allows($method); $Foo{$self}->$method; }; sub DESTROY { my $self = shift; delete $Foo{$self}; }; };
Hope this helps.
In reply to Re: Filtering access to an Objects functions
by adrianh
in thread Filtering access to an Objects functions
by CTSMan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |