in reply to OO: extending a closure object

Check to see if you're being asked to do something that you know how to do, if so, handle it. If not, let the object you wrapped handle it. I made a small modification: the $self hash reference didn't need to be a reference so I promoted it to a regular hash. Your closure closes over that just fine.

That is, the basic technique is wrapping and delegation. That's it. There's no special magic involved because it's a closure or because %self is a hash or a hash reference. That's probably why you didn't find anything specifically about this, it's a general technique and not something that requires anything new of you.

package YourExtension; use base 'TheOriginal'; sub new { my $class = shift; my $extended = $class->SUPER::new( @_ ); my %self = ( CELLULAR => undef, EMAIL => undef, ); my $closure = sub { my $field = shift; if ( exists $self{$field} ) { if ( @_ ) { $self{$field} = shift } return $self{$field}; } else { return $extended->$field( @_ ); } }; bless( $closure, $class ); return $closure; }

⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Replies are listed 'Best First'.
Re^2: OO: extending a closure object
by gargle (Chaplain) on Feb 23, 2006 at 08:18 UTC

    I see one problem here;

    return $extended->$field( @_ );

    requires that my setters in the base class are called exactly as the field names. Otherwise it won't work :(

    p.e. in my base class I have a field ACCOUNT and a setter called setAccount. The constructor above will however call my base class as $extended->ACCOUNT instead of $extended->setAccount.

    --
    if ( 1 ) { $postman->ring() for (1..2); }
      I think that was supposed to be
      return $extended->($field, @_);

      Caution: Contents may have been coded under pressure.