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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.