gv11ng has asked for the wisdom of the Perl Monks concerning the following question:

Hi! I cannot solve one problem. My project contains many modules. MIME::Lite is used in several of them. I want method MIME::Lite->send() to be called with my default values in all cases. I know the decision if the call is occurred in one module but what is to be done in such situation (the call in a lot of places). As I think it’s bad decision to change code of MIME::Lite. What can you advice me? Thanks a lot!

Replies are listed 'Best First'.
Re: Overriding of a method
by jhourcle (Prior) on Nov 30, 2005 at 15:23 UTC

    There's a couple of options. If you're creating instances of the objects, rather than just calling methods in the namespace, you can use inheritance:

    use My::MIME::Lite; my $mime = My::MIME::Lite->new() $mime->send() ##### package My::MIME::Lite; use base qw(MIME::Lite); sub send { my $self=shift; # override the behavior here. You can call $self->MIME::Lite::send( +) # or $self->SUPER::send() } 1;

    or, if you don't mind the warning, you can redeclare the method, in the original namespace (this is very bad, if you're using mod_perl, or something else where multiple scripts share the same modules)

    use MIME::Lite; sub MIME::Lite::send { # do whatever here, but you can't call back to the 'real' MIME::Lite +::send }
      Thanks for replies. Unfortunately I have asked the question incorrectly. Is it a method which allows not to change code in my modules for the call MIME::Lite->send() method.(i.e. use MIME::Lite rather than My::MIME::Lite)?

        Yes. You can directly insert your new method into the symbol table. But it is not recommended. It makes your code hard to follow, hard to debug and unpredictable. Do you know for example what methods inside Mime::Lite might be expecting the 'send' method to have the documented behaviour? Are there other modules you are using that expect Mime::Lite::send to have the documented behaviour?

        Besides all that, it's ugly.

        But if I haven't put you off by my little rant above and you still want do to it, here is one of the ways:

        *MIME::Lite::send = sub { ... your code here ....}

        Update: Of course, another way of doing it is at the bottom of jhourcle's post.

Re: Overriding of a method
by dragonchild (Archbishop) on Nov 30, 2005 at 15:21 UTC
    package My::MIME::Lite; use base 'MIME::Lite'; my %defaults = ( # your defaults here ); sub send { my $self = shift; return $self->SUPER::send( @_, %defaults ); } 1;

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?