Phoenix.pm: package Autoloading

Beaves at aol.com Beaves at aol.com
Wed Oct 20 09:42:11 CDT 1999


I talked about a certain AUTOLOAD technique at the meeting.  There are 
others, but this seemed to suit my particular situation.

My problem was that I wanted to just be able to call

FormVar::Text->new()  # for example,

without having to worry about whether or not the FormVar::Text package (also 
read file) was required already.  If FormVar::Text is a completely empty and 
undefined package at the time of calling new(), then you will always get an 
error, because it cant find new, and has no information on where else to look.

So, my (I'm sure unoriginal) idea was to use an AUTOLOAD routine in a package 
whose only reason for existence is to AUTOLOAD the FormVar packages.  I call 
this package LoadMe for lack of a better name.  The LoadMe package AUTOLOAD 
routine parses the package name out of the called method (in the $AUTOLOAD( 
variable), requires the package, and then calls the method again.  The 
package called should then reassign @ISA, since you don't want 'LoadMe' as a 
parent anymore.

***** The Code *****

package FormVar;

# all of the possible packages that could be called.
@FormVar_Packages = ( qw(
    FormVar::Text
    FormVar::Password
    FormVar::Checkbox
    FormVar::CheckboxGroup
    FormVar::Button
    FormVar::SubmitButton
    FormVar::Option
    FormVar::OptionGroup
    FormVar::Radio
    FormVar::VarGroup
    FormVar::ERR
    FormVar::SelectList
    FormVar::SelectListMultiple
    FormVar::Cluster
    FormVar::Textarea
    FormVar::Page
));

# To make this work, we need each package already built with an @ISA pointing 
to
# 'FormVar::LoadMe'

map { @{"$_\::ISA"} = ('FormVar::LoadMe') }  @FormVar_Packages;  # @ISA will 
be overwritten in file

# Now for the 'LoadMe' AUTOLOAD routine...

package FormVar::LoadMe;

sub AUTOLOAD  {
    my $self = $_[0];
    my $class = ref($self) || $self;
# use and eval to capture an error and spit out something more meaningful.
    eval ("require HTML::$class");
    $@ and die "AZWEBS ERROR: error in requiring '$class' (error 
follows)...\n$@";

# now lets try the same method call again with the same arguments
# You will get an error if you don't reassign @ISA in the required package
# as this then becomes recursive.

    &{$AUTOLOAD}(@_)

}

# Then return to the FormVar package definitions
package FormVar;

***** End Code *****

If anyone has any questions, give me a buzz!!

Check 6!

Tim




More information about the Phoenix-pm mailing list