SEARCH
NEW RPMS
DIRECTORIES
ABOUT
FAQ
VARIOUS
BLOG
DONATE


YUM REPOSITORY

 
 

MAN page from Fedora 28 perl-Class-Autouse-2.01-18.fc28.noarch.rpm

Class::Autouse

Section: User Contributed Perl Documentation (3)
Updated: 2012-02-03
Index 

NAME

Class::Autouse - Run-time load a class the first time you call a method in it. 

SYNOPSIS

    ##################################################################    # SAFE FEATURES    # Debugging (if you go that way) must be set before the first use    BEGIN {        $Class::Autouse::DEBUG = 1;    }    # Turn on developer mode (always load immediately)    use Class::Autouse qw{:devel};    # Load a class on method call    use Class::Autouse;    Class::Autouse->autouse( 'CGI' );    print CGI->b('Wow!');    # Use as a pragma    use Class::Autouse qw{CGI};    # Use a whole module tree    Class::Autouse->autouse_recursive('Acme');    # Disable module-existance check, and thus one additional 'stat'    # per module, at autouse-time if loading modules off a remote    # network drive such as NFS or SMB.    # (See below for other performance optimizations.)    use Class::Autouse qw{:nostat};    ##################################################################    # UNSAFE FEATURES    # Turn on the Super Loader (load all classes on demand)    use Class::Autouse qw{:superloader};    # Autouse classes matching a given regular expression    use Class::Autouse qr/::Test$/;    # Install a class generator (instead of overriding UNIVERSAL::AUTOLOAD)    # (See below for a detailed example)    use Class::Autouse \&my_class_generator;    # Add a manual callback to UNIVERSAL::AUTOLOAD for syntactic sugar    Class::Autouse->sugar(\&my_magic);
 

DESCRIPTION

Class::Autouse is a runtime class loader that allows you to specifyclasses that will only load when a method of that class is called.

For large classes or class trees that might not be used during the runningof a program, such as Date::Manip, this can save you large amounts ofmemory, and decrease the script load time a great deal.

Class::Autouse also provides a number of ``unsafe'' features for runtimegeneration of classes and implementation of syntactic sugar. These featuresmake use of (evil) UNIVERSAL::AUTOLOAD hooking, and are implemented inthis class because these hooks can only be done by a one module, andClass::Autouse serves as a useful place to centralise this kind of evil :) 

Class, not Module

The terminology ``class loading'' instead of ``module loading'' is usedintentionally. Modules will only be loaded if they are acting as a class.

That is, they will only be loaded during a Class->method call. If you tryto use a subroutine directly, say with "Class::method()", the class willnot be loaded and a fatal error will mostly likely occur.

This limitation is made to allow more powerfull features in other areas,because we can focus on just loading the modules, and not haveto deal with importing.

And really, if you are doing OO Perl, you should be avoiding importingwherever possible. 

Use as a pragma

Class::Autouse can be used as a pragma, specifying a list of classesto load as the arguments. For example

   use Class::Autouse qw{CGI Data::Manip This::That};

is equivalent to

   use Class::Autouse;   Class::Autouse->autouse( 'CGI'         );   Class::Autouse->autouse( 'Data::Manip' );   Class::Autouse->autouse( 'This::That'  );
 

Developer Mode

"Class::Autouse" features a developer mode. In developer mode, classesare loaded immediately, just like they would be with a normal 'use'statement (although the import sub isn't called).

This allows error checking to be done while developing, at the expense ofa larger memory overhead. Developer mode is turned on either with the"devel" method, or using :devel in any of the pragma arguments.For example, this would load CGI.pm immediately

    use Class::Autouse qw{:devel CGI};

While developer mode is roughly equivalent to just using a normal usecommand, for a large number of modules it lets you use autoloadingnotation, and just comment or uncomment a single line to turn developermode on or off. You can leave it on during development, and turn itoff for speed reasons when deploying. 

Recursive Loading

As an alternative to the super loader, the "autouse_recursive" and"load_recursive" methods can be used to autouse or load an entire treeof classes.

For example, the following would give you access to all the URIrelated classes installed on the machine.

    Class::Autouse->autouse_recursive( 'URI' );

Please note that the loadings will only occur down a single branch of theinclude path, whichever the top class is located in. 

No-Stat Mode

For situations where a module exists on a remote disk or another relativelyexpensive location, you can call "Class::Autouse" with the :nostat paramto disable initial file existance checking at hook time.

  # Disable autoload-time file existance checking  use Class::Autouse qw{:nostat};
 

Super Loader Mode

Turning on the "Class::Autouse" super loader allows you to automaticallyload ANY class without specifying it first. Thus, the following willwork and is completely legal.

    use Class::Autouse qw{:superloader};    print CGI->b('Wow!');

The super loader can be turned on with either the"Class::Autouse->"superloader> method, or the ":superloader" pragmaargument.

Please note that unlike the normal one-at-a-time autoloading, thesuper-loader makes global changes, and so is not completely self-contained.

It has the potential to cause unintended effects at a distance. If youencounter unusual behaviour, revert to autousing one-at-a-time, or usethe recursive loading.

Use of the Super Loader is highly discouraged for widely distributedpublic applications or modules unless unavoidable. Do not use justto be lazy and save a few lines of code. 

Loading with Regular Expressions

As another alternative to the superloader and recursive loading, a compiledregular expression (qr//) can be supplied as a loader. Note that thisloader implements UNIVERSAL::AUTOLOAD, and has the same side effects as thesuperloader. 

Registering a Callback for Dynamic Class Creation

If none of the above are sufficient, a CODE reference can be givento Class::Autouse. Any attempt to call a method on a missing classwill launch each registered callback until one returns true.

Since overriding UNIVERSAL::AUTOLOAD can be done only once in a givenPerl application, this feature allows UNIVERSAL::AUTOLOAD to be shared.Please use this instead of implementing your own UNIVERSAL::AUTOLOAD.

See the warnings under the ``Super Loader Module'' above whichapply to all of the features which override UNIVERSAL::AUTOLOAD.

It is up to the callback to define the class, the details of whichare beyond the scope of this document. See the example below fora quick reference:

Callback Example

Any use of a class like Foo::Wrapper autogenerates that class as a proxyaround Foo.

    use Class::Autouse sub {        my ($class) = @_;        if ($class =~ /(^.*)::Wrapper/) {            my $wrapped_class = $1;            eval "package $class; use Class::AutoloadCAN;";            die $@ if $@;            no strict 'refs';            *{$class . '::new' } = sub {                my $class = shift;                my $proxy = $wrapped_class->new(@_);                my $self = bless({proxy => $proxy},$class);                return $self;            };            *{$class . '::CAN' } = sub {                my ($obj,$method) = @_;                my $delegate = $wrapped_class->can($method);                return unless $delegate;                my $delegator = sub {                    my $self = shift;                    if (ref($self)) {                        return $self->{proxy}->$method(@_);                    }                    else {                        return $wrapped_class->$method(@_);                    }                };                return *{ $class . '::' . $method } = $delegator;            };            return 1;        }        return;    };    package Foo;    sub new { my $class = shift; bless({@_},$class); }    sub class_method { 123 }    sub instance_method {        my ($self,$v) = @_;        return $v * $self->some_property    }    sub some_property { shift->{some_property} }    package main;    my $x = Foo::Wrapper->new(        some_property => 111,    );    print $x->some_property,"\n";    print $x->instance_method(5),"\n";    print Foo::Wrapper->class_method,"\n";
 

sugar

This method is provided to support ``syntactic sugar'': allowing the developerto put things into Perl which do not look like regular Perl. There areseveral ways to do this in Perl. Strategies which require overridingUNIVERSAL::AUTOLOAD can use this interface instead to share that methodwith the superloader, and with class gnerators.

When Perl is unable to find a subroutine/method, and all of the class loadersare exhausted, callbacks registered via sugar() are called. The callbacksrecieve the class name, method name, and parameters of the call.

If the callback returns nothing, Class::Autouse will continue to iterate throughother callbacks. The first callback which returns a true value willend iteration. That value is expected to be a CODE reference which will respondto the AUTOLOAD call.

Note: The sugar callback(s) will only be fired by UNIVERSAL::AUTOLOAD after allother attempts at loading the class are done, and after attempts to use regularAUTOLOAD to handle the method call. It is never fired by isa() or can(). Itwill fire repatedly for the same class. To generate classes, use theregular CODE ref support in autouse().

Syntactic Sugar Example

    use Class::Autouse;    Class::Autouse->sugar(        sub {            my $caller = caller(1);            my ($class,$method,@params) = @_;            shift @params;            my @words = ($method,$class,@params);            my $sentence = join(" ",@words);            return sub { $sentence };        }    );    $x = trolls have big ugly hairy feet;    print $x,"\n";    # trolls have big ugly hairy feet
 

mod_perl

The mechanism that "Class::Autouse" uses is not compatible with mod_perl.In particular with reloader modules like Apache::Reload. "Class::Autouse"detects the presence of mod_perl and acts as normal, but will always loadall classes immediately, equivalent to having developer mode enabled.

This is actually beneficial, as under mod_perl classes should be preloadedin the parent mod_perl process anyway, to prevent them having to be loadedby the Apache child classes. It also saves HUGE amounts of memory.

Note that dynamically generated classes and classes loaded via regex CANNOTbe pre-loaded automatically before forking child processes. They will stillbe loaded on demand, often in the child process. See prefork below. 

prefork

As with mod_perl, "Class::Autouse" is compatible with the prefork module,and all modules specifically autoloaded will be loaded before forking correctly,when requested by prefork.

Since modules generated via callback or regex cannot be loaded automaticallyby prefork in a generic way, it's advised to use prefork directly to load/generateclasses when using mod_perl. 

Performance Optimizatons

:nostat
Described above, this option is useful when the module in question is onremote disk.
:noprebless
When set, Class::Autouse presumes that objects which are already blessedhave their class loaded.

This is true in most cases, but will break if the developer intends toreconstitute serialized objects from Data::Dumper, FreezeThaw or itscousins, and has configured Class::Autouse to load the involved classesjust-in-time.

:staticisa
When set, presumes that @ISA will not change for a class once it is loaded.The greatest grandparent of a class will be given back the original can/isaimplementations which are faster than those Class::Autouse installs intoUNIVERSAL. This is a performance tweak useful in most cases, but is leftoff by default to prevent obscure bugs.
 

The Internal Debugger

Class::Autouse provides an internal debugger, which can be used to debugany weird edge cases you might encounter when using it.

If the $Class::Autouse::DEBUG variable is true when "Class::Autouse"is first loaded, debugging will be compiled in. This debugging printsoutput like the following to STDOUT.

    Class::Autouse::autouse_recursive( 'Foo' )        Class::Autouse::_recursive( 'Foo', 'load' )            Class::Autouse::load( 'Foo' )            Class::Autouse::_children( 'Foo' )            Class::Autouse::load( 'Foo::Bar' )                Class::Autouse::_file_exists( 'Foo/Bar.pm' )                Class::Autouse::load -> Loading in Foo/Bar.pm            Class::Autouse::load( 'Foo::More' )                etc...

Please note that because this is optimised out if not used, you canno longer (since 1.20) enable debugging at run-time. This decision wasmade to remove a large number of unneeded branching and speed up loading. 

METHODS

 

autouse $class, ...

The autouse method sets one or more classes to be loaded as required. 

load $class

The load method loads one or more classes into memory. This is functionallyequivalent to using require to load the class list in, except that loadwill detect and remove the autoloading hook from a previously autousedclass, whereas as use effectively ignore the class, and not load it. 

devel

The devel method sets development mode on (argument of 1) or off(argument of 0).

If any classes have previously been autouse'd and not loaded when thismethod is called, they will be loaded immediately. 

superloader

The superloader method turns on the super loader.

Please note that once you have turned the superloader on, it cannot beturned off. This is due to code that might be relying on it being there notbeing able to autoload its classes when another piece of code decidesthey don't want it any more, and turns the superloader off. 

class_exists $class

Handy method when doing the sort of jobs that "Class::Autouse" does. Givena class name, it will return true if the class can be loaded ( i.e. in @INC ),false if the class can't be loaded, and undef if the class name is invalid.

Note that this does not actually load the class, just tests to see if it canbe loaded. Loading can still fail. For a more comprehensive set of methodsof this nature, see Class::Inspector. 

autouse_recursive $class

The same as the "autouse" method, but autouses recursively. 

load_recursive $class

The same as the "load" method, but loads recursively. Great for checking thata large class tree that might not always be loaded will load correctly. 

SUPPORT

Bugs should be always be reported via the CPAN bug tracker at

<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Class-Autouse>

For other issues, or commercial enhancement or support, contact the author. 

AUTHORS

Adam Kennedy <cpanAATTali.as>

Scott Smith <sakohtAATTcpan.org>

Rob Napier <rnapierAATTemployees.org> 

SEE ALSO

autoload, autoclass 

COPYRIGHT

Copyright 2002 - 2012 Adam Kennedy.

This program is free software; you can redistributeit and/or modify it under the same terms as Perl itself.

The full text of the license can be found in theLICENSE file included with this module.


 

Index

NAME
SYNOPSIS
DESCRIPTION
Class, not Module
Use as a pragma
Developer Mode
Recursive Loading
No-Stat Mode
Super Loader Mode
Loading with Regular Expressions
Registering a Callback for Dynamic Class Creation
sugar
mod_perl
prefork
Performance Optimizatons
The Internal Debugger
METHODS
autouse $class, ...
load $class
devel
superloader
class_exists $class
autouse_recursive $class
load_recursive $class
SUPPORT
AUTHORS
SEE ALSO
COPYRIGHT

This document was created byman2html,using the manual pages.