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

I am designing a module set that I may want to some day be published on CPAN. It will contain components that I know would need to be overridden if used elsewhere, such as logging or database access. I would like for someone to be able to create their overriding logging class, use it and then use my class. My class would then use the overridden class instead of my own.

How do I do this or advise the overriding class to be written? Are there standard references that say how to do this? Are there standard modules that would help with this? Do I need to write an AUTOLOAD method?

Replies are listed 'Best First'.
Re: Polymorphism through use
by kyle (Abbot) on Jan 24, 2009 at 01:41 UTC

    Say your module set is Dpommert::Module, and I'm writing Kyle::Logger. I'd probably set it up this way.

    package Kyle::Logger; use Dpommert::Module; Dpommert::Module->set_default_logger( __PACKAGE__ ); package Dpommert::Module; my $default_logger_class = 'Dpommert::Logger'; sub set_default_logger { my $class = shift; die 'class method' if ref $class; $default_logger_class = shift; } sub get_logger { my $self = shift; return $self->{logger} ||= $default_logger_class->new(); } sub set_logger { my $self = shift; $self->{logger} = shift; }

    In set_logger and set_default_logger, you may want to use UNIVERSAL::can to make sure what you get has the interface you need.

    The way the above works is that a logger class, when it's used, registers itself with the module set. On top of that, any instance of the module can have its logger changed from the default. In this scenario, it's important that Dpommert::Module is used first, contrary to the usage you laid out.