Overriding object methods (sometimes)
Andy Armstrong
andy at hexten.net
Mon Feb 25 17:49:12 GMT 2008
On 25 Feb 2008, at 17:25, 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?
It might be cleaner to make your class into a wrapper around an
LWP::UserAgent instance rather than a subclass of it. So that $self-
>SUPER::request() would become $self->{_lwp}->request(). Then LWP
will despatch normally to its own methods.
For any methods that you want to pass through you can use AUTOLOAD or
some similar magic.
So basically write a proxy for LWP::UserAgent.
--
Andy Armstrong, Hexten
More information about the london.pm
mailing list