1Class::Autouse(3) User Contributed Perl Documentation Class::Autouse(3)
2
3
4
6 Class::Autouse - Run-time load a class the first time you call a method
7 in it.
8
10 ##################################################################
11 # SAFE FEATURES
12
13 # Debugging (if you go that way) must be set before the first use
14 BEGIN {
15 $Class::Autouse::DEBUG = 1;
16 }
17
18 # Turn on developer mode (always load immediately)
19 use Class::Autouse qw{:devel};
20
21 # Load a class on method call
22 use Class::Autouse;
23 Class::Autouse->autouse( 'CGI' );
24 print CGI->b('Wow!');
25
26 # Use as a pragma
27 use Class::Autouse qw{CGI};
28
29 # Use a whole module tree
30 Class::Autouse->autouse_recursive('Acme');
31
32 # Disable module-existance check, and thus one additional 'stat'
33 # per module, at autouse-time if loading modules off a remote
34 # network drive such as NFS or SMB.
35 # (See below for other performance optimizations.)
36 use Class::Autouse qw{:nostat};
37
38
39
40
41
42 ##################################################################
43 # UNSAFE FEATURES
44
45 # Turn on the Super Loader (load all classes on demand)
46 use Class::Autouse qw{:superloader};
47
48 # Autouse classes matching a given regular expression
49 use Class::Autouse qr/::Test$/;
50
51 # Install a class generator (instead of overriding UNIVERSAL::AUTOLOAD)
52 # (See below for a detailed example)
53 use Class::Autouse \&my_class_generator;
54
55 # Add a manual callback to UNIVERSAL::AUTOLOAD for syntactic sugar
56 Class::Autouse->sugar(\&my_magic);
57
59 Class::Autouse is a runtime class loader that allows you to specify
60 classes that will only load when a method of that class is called.
61
62 For large classes or class trees that might not be used during the
63 running of a program, such as Date::Manip, this can save you large
64 amounts of memory, and decrease the script load time a great deal.
65
66 Class::Autouse also provides a number of "unsafe" features for runtime
67 generation of classes and implementation of syntactic sugar. These
68 features make use of (evil) UNIVERSAL::AUTOLOAD hooking, and are
69 implemented in this class because these hooks can only be done by a one
70 module, and Class::Autouse serves as a useful place to centralise this
71 kind of evil :)
72
73 Class, not Module
74 The terminology "class loading" instead of "module loading" is used
75 intentionally. Modules will only be loaded if they are acting as a
76 class.
77
78 That is, they will only be loaded during a Class->method call. If you
79 try to use a subroutine directly, say with "Class::method()", the class
80 will not be loaded and a fatal error will mostly likely occur.
81
82 This limitation is made to allow more powerfull features in other
83 areas, because we can focus on just loading the modules, and not have
84 to deal with importing.
85
86 And really, if you are doing OO Perl, you should be avoiding importing
87 wherever possible.
88
89 Use as a pragma
90 Class::Autouse can be used as a pragma, specifying a list of classes to
91 load as the arguments. For example
92
93 use Class::Autouse qw{CGI Data::Manip This::That};
94
95 is equivalent to
96
97 use Class::Autouse;
98 Class::Autouse->autouse( 'CGI' );
99 Class::Autouse->autouse( 'Data::Manip' );
100 Class::Autouse->autouse( 'This::That' );
101
102 Developer Mode
103 "Class::Autouse" features a developer mode. In developer mode, classes
104 are loaded immediately, just like they would be with a normal 'use'
105 statement (although the import sub isn't called).
106
107 This allows error checking to be done while developing, at the expense
108 of a larger memory overhead. Developer mode is turned on either with
109 the "devel" method, or using :devel in any of the pragma arguments.
110 For example, this would load CGI.pm immediately
111
112 use Class::Autouse qw{:devel CGI};
113
114 While developer mode is roughly equivalent to just using a normal use
115 command, for a large number of modules it lets you use autoloading
116 notation, and just comment or uncomment a single line to turn developer
117 mode on or off. You can leave it on during development, and turn it off
118 for speed reasons when deploying.
119
120 Recursive Loading
121 As an alternative to the super loader, the "autouse_recursive" and
122 "load_recursive" methods can be used to autouse or load an entire tree
123 of classes.
124
125 For example, the following would give you access to all the URI related
126 classes installed on the machine.
127
128 Class::Autouse->autouse_recursive( 'URI' );
129
130 Please note that the loadings will only occur down a single branch of
131 the include path, whichever the top class is located in.
132
133 No-Stat Mode
134 For situations where a module exists on a remote disk or another
135 relatively expensive location, you can call "Class::Autouse" with the
136 :nostat param to disable initial file existance checking at hook time.
137
138 # Disable autoload-time file existance checking
139 use Class::Autouse qw{:nostat};
140
141 Super Loader Mode
142 Turning on the "Class::Autouse" super loader allows you to
143 automatically load ANY class without specifying it first. Thus, the
144 following will work and is completely legal.
145
146 use Class::Autouse qw{:superloader};
147
148 print CGI->b('Wow!');
149
150 The super loader can be turned on with either the
151 "Class::Autouse->"superloader> method, or the ":superloader" pragma
152 argument.
153
154 Please note that unlike the normal one-at-a-time autoloading, the
155 super-loader makes global changes, and so is not completely self-
156 contained.
157
158 It has the potential to cause unintended effects at a distance. If you
159 encounter unusual behaviour, revert to autousing one-at-a-time, or use
160 the recursive loading.
161
162 Use of the Super Loader is highly discouraged for widely distributed
163 public applications or modules unless unavoidable. Do not use just to
164 be lazy and save a few lines of code.
165
166 Loading with Regular Expressions
167 As another alternative to the superloader and recursive loading, a
168 compiled regular expression (qr//) can be supplied as a loader. Note
169 that this loader implements UNIVERSAL::AUTOLOAD, and has the same side
170 effects as the superloader.
171
172 Registering a Callback for Dynamic Class Creation
173 If none of the above are sufficient, a CODE reference can be given to
174 Class::Autouse. Any attempt to call a method on a missing class will
175 launch each registered callback until one returns true.
176
177 Since overriding UNIVERSAL::AUTOLOAD can be done only once in a given
178 Perl application, this feature allows UNIVERSAL::AUTOLOAD to be shared.
179 Please use this instead of implementing your own UNIVERSAL::AUTOLOAD.
180
181 See the warnings under the "Super Loader Module" above which apply to
182 all of the features which override UNIVERSAL::AUTOLOAD.
183
184 It is up to the callback to define the class, the details of which are
185 beyond the scope of this document. See the example below for a quick
186 reference:
187
188 Callback Example
189
190 Any use of a class like Foo::Wrapper autogenerates that class as a
191 proxy around Foo.
192
193 use Class::Autouse sub {
194 my ($class) = @_;
195 if ($class =~ /(^.*)::Wrapper/) {
196 my $wrapped_class = $1;
197 eval "package $class; use Class::AutoloadCAN;";
198 die $@ if $@;
199 no strict 'refs';
200 *{$class . '::new' } = sub {
201 my $class = shift;
202 my $proxy = $wrapped_class->new(@_);
203 my $self = bless({proxy => $proxy},$class);
204 return $self;
205 };
206 *{$class . '::CAN' } = sub {
207 my ($obj,$method) = @_;
208 my $delegate = $wrapped_class->can($method);
209 return unless $delegate;
210 my $delegator = sub {
211 my $self = shift;
212 if (ref($self)) {
213 return $self->{proxy}->$method(@_);
214 }
215 else {
216 return $wrapped_class->$method(@_);
217 }
218 };
219 return *{ $class . '::' . $method } = $delegator;
220 };
221
222 return 1;
223 }
224 return;
225 };
226
227 package Foo;
228 sub new { my $class = shift; bless({@_},$class); }
229 sub class_method { 123 }
230 sub instance_method {
231 my ($self,$v) = @_;
232 return $v * $self->some_property
233 }
234 sub some_property { shift->{some_property} }
235
236
237 package main;
238 my $x = Foo::Wrapper->new(
239 some_property => 111,
240 );
241 print $x->some_property,"\n";
242 print $x->instance_method(5),"\n";
243 print Foo::Wrapper->class_method,"\n";
244
245 sugar
246 This method is provided to support "syntactic sugar": allowing the
247 developer to put things into Perl which do not look like regular Perl.
248 There are several ways to do this in Perl. Strategies which require
249 overriding UNIVERSAL::AUTOLOAD can use this interface instead to share
250 that method with the superloader, and with class gnerators.
251
252 When Perl is unable to find a subroutine/method, and all of the class
253 loaders are exhausted, callbacks registered via sugar() are called.
254 The callbacks recieve the class name, method name, and parameters of
255 the call.
256
257 If the callback returns nothing, Class::Autouse will continue to
258 iterate through other callbacks. The first callback which returns a
259 true value will end iteration. That value is expected to be a CODE
260 reference which will respond to the AUTOLOAD call.
261
262 Note: The sugar callback(s) will only be fired by UNIVERSAL::AUTOLOAD
263 after all other attempts at loading the class are done, and after
264 attempts to use regular AUTOLOAD to handle the method call. It is
265 never fired by isa() or can(). It will fire repatedly for the same
266 class. To generate classes, use the regular CODE ref support in
267 autouse().
268
269 Syntactic Sugar Example
270
271 use Class::Autouse;
272 Class::Autouse->sugar(
273 sub {
274 my $caller = caller(1);
275 my ($class,$method,@params) = @_;
276 shift @params;
277 my @words = ($method,$class,@params);
278 my $sentence = join(" ",@words);
279 return sub { $sentence };
280 }
281 );
282
283 $x = trolls have big ugly hairy feet;
284
285 print $x,"\n";
286 # trolls have big ugly hairy feet
287
288 mod_perl
289 The mechanism that "Class::Autouse" uses is not compatible with
290 mod_perl. In particular with reloader modules like Apache::Reload.
291 "Class::Autouse" detects the presence of mod_perl and acts as normal,
292 but will always load all classes immediately, equivalent to having
293 developer mode enabled.
294
295 This is actually beneficial, as under mod_perl classes should be
296 preloaded in the parent mod_perl process anyway, to prevent them having
297 to be loaded by the Apache child classes. It also saves HUGE amounts of
298 memory.
299
300 Note that dynamically generated classes and classes loaded via regex
301 CANNOT be pre-loaded automatically before forking child processes.
302 They will still be loaded on demand, often in the child process. See
303 prefork below.
304
305 prefork
306 As with mod_perl, "Class::Autouse" is compatible with the prefork
307 module, and all modules specifically autoloaded will be loaded before
308 forking correctly, when requested by prefork.
309
310 Since modules generated via callback or regex cannot be loaded
311 automatically by prefork in a generic way, it's advised to use prefork
312 directly to load/generate classes when using mod_perl.
313
314 Performance Optimizatons
315 :nostat
316 Described above, this option is useful when the module in question
317 is on remote disk.
318
319 :noprebless
320 When set, Class::Autouse presumes that objects which are already
321 blessed have their class loaded.
322
323 This is true in most cases, but will break if the developer intends
324 to reconstitute serialized objects from Data::Dumper, FreezeThaw or
325 its cousins, and has configured Class::Autouse to load the involved
326 classes just-in-time.
327
328 :staticisa
329 When set, presumes that @ISA will not change for a class once it is
330 loaded. The greatest grandparent of a class will be given back the
331 original can/isa implementations which are faster than those
332 Class::Autouse installs into UNIVERSAL. This is a performance
333 tweak useful in most cases, but is left off by default to prevent
334 obscure bugs.
335
336 The Internal Debugger
337 Class::Autouse provides an internal debugger, which can be used to
338 debug any weird edge cases you might encounter when using it.
339
340 If the $Class::Autouse::DEBUG variable is true when "Class::Autouse" is
341 first loaded, debugging will be compiled in. This debugging prints
342 output like the following to STDOUT.
343
344 Class::Autouse::autouse_recursive( 'Foo' )
345 Class::Autouse::_recursive( 'Foo', 'load' )
346 Class::Autouse::load( 'Foo' )
347 Class::Autouse::_children( 'Foo' )
348 Class::Autouse::load( 'Foo::Bar' )
349 Class::Autouse::_file_exists( 'Foo/Bar.pm' )
350 Class::Autouse::load -> Loading in Foo/Bar.pm
351 Class::Autouse::load( 'Foo::More' )
352 etc...
353
354 Please note that because this is optimised out if not used, you can no
355 longer (since 1.20) enable debugging at run-time. This decision was
356 made to remove a large number of unneeded branching and speed up
357 loading.
358
360 autouse $class, ...
361 The autouse method sets one or more classes to be loaded as required.
362
363 load $class
364 The load method loads one or more classes into memory. This is
365 functionally equivalent to using require to load the class list in,
366 except that load will detect and remove the autoloading hook from a
367 previously autoused class, whereas as use effectively ignore the class,
368 and not load it.
369
370 devel
371 The devel method sets development mode on (argument of 1) or off
372 (argument of 0).
373
374 If any classes have previously been autouse'd and not loaded when this
375 method is called, they will be loaded immediately.
376
377 superloader
378 The superloader method turns on the super loader.
379
380 Please note that once you have turned the superloader on, it cannot be
381 turned off. This is due to code that might be relying on it being there
382 not being able to autoload its classes when another piece of code
383 decides they don't want it any more, and turns the superloader off.
384
385 class_exists $class
386 Handy method when doing the sort of jobs that "Class::Autouse" does.
387 Given a class name, it will return true if the class can be loaded (
388 i.e. in @INC ), false if the class can't be loaded, and undef if the
389 class name is invalid.
390
391 Note that this does not actually load the class, just tests to see if
392 it can be loaded. Loading can still fail. For a more comprehensive set
393 of methods of this nature, see Class::Inspector.
394
395 autouse_recursive $class
396 The same as the "autouse" method, but autouses recursively.
397
398 load_recursive $class
399 The same as the "load" method, but loads recursively. Great for
400 checking that a large class tree that might not always be loaded will
401 load correctly.
402
404 Bugs should be always be reported via the CPAN bug tracker at
405
406 <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Class-Autouse>
407
408 For other issues, or commercial enhancement or support, contact the
409 author.
410
412 Adam Kennedy <cpan@ali.as>
413
414 Scott Smith <sakoht@cpan.org>
415
416 Rob Napier <rnapier@employees.org>
417
419 autoload, autoclass
420
422 Copyright 2002 - 2012 Adam Kennedy.
423
424 This program is free software; you can redistribute it and/or modify it
425 under the same terms as Perl itself.
426
427 The full text of the license can be found in the LICENSE file included
428 with this module.
429
430
431
432perl v5.32.1 2021-01-26 Class::Autouse(3)