Overriding object methods (sometimes)

Matt Lawrence matt.lawrence at virgin.net
Mon Feb 25 18:08:57 GMT 2008


Bradley Dean wrote:
> Greetings folks,
>
> I've recently had cause to wrap LWP::UserAgent in a child class
> which needs to override most public methods. In doing so I've hit up
> against a problem - these requests call each other, but I only want my
> child-class methods to be called when I call them.
>
> My solution was to check the caller and respond appropriately, for
> instance:
>
> sub request {
>   my ($self, @params) = @_;
>   my ($package, $filename, $line) = caller();
>   if ( $package eq 'LWP::UserAgent' ) {
>     return $self->SUPER::request(@params);
>   }
>   else {
>     return $self->_wrapper(\&LWP::UserAgent::request, @params)
>   }
> }
>
> Where &_wrapper contains my local logic (it's taking a reference
> to &LWP::UserAgent::request because it's going to call it later on).
>   
> This works fine, and isn't overly ugly, but I'm wondering if I've missed or
> forgotten a nicer way to do it. :)
>
> Any thoughts?
>   

Sounds like it might be easier to do this using composition instead of 
inheritance, possibly using AUTOLOAD to dispatch to methods in your 
contained object that you haven't overridden.

# $self->lwp is your LWP::UserAgent object
sub request {
    my ($self, @params) = @_;
    $self->_wrapper($self->lwp->can('request'), @params);
}


Matt



More information about the london.pm mailing list