Debian Codegraph @

README

raw
1 NAME
2 Class::Base - useful base class for deriving other modules
3
4 SYNOPSIS
5 package My::Funky::Module;
6 use base qw( Class::Base );
7
8 # custom initialiser method
9 sub init {
10 my ($self, $config) = @_;
11
12 # copy various params into $self
13 $self->params($config, qw( FOO BAR BAZ ))
14 || return undef;
15
16 # to indicate a failure
17 return $self->error('bad constructor!')
18 if $something_bad;
19
20 # or to indicate general happiness and well-being
21 return $self;
22 }
23
24 package main;
25
26 # new() constructor folds args into hash and calls init()
27 my $object = My::Funky::Module->new( foo => 'bar', ... )
28 || die My::Funky::Module->error();
29
30 # error() class/object method to get/set errors
31 $object->error('something has gone wrong');
32 print $object->error();
33
34 # debugging() method (de-)activates the debug() method
35 $object->debugging(1);
36
37 # debug() prints to STDERR if debugging enabled
38 $object->debug('The ', $animal, ' sat on the ', $place);
39
40 DESCRIPTION
41 This module implements a simple base class from which other modules can
42 be derived, thereby inheriting a number of useful methods such as
43 "new()", "init()", "params()", "clone()", "error()" and "debug()".
44
45 For a number of years, I found myself re-writing this module for
46 practically every Perl project of any significant size. Or rather, I
47 would copy the module from the last project and perform a global search
48 and replace to change the names. Each time it got a little more polished
49 and eventually, I decided to Do The Right Thing and release it as a
50 module in it's own right.
51
52 It doesn't pretend to be an all-encompassing solution for every kind of
53 object creation problem you might encounter. In fact, it only supports
54 blessed hash references that are created using the popular, but by no
55 means universal convention of calling "new()" with a list or reference
56 to a hash array of named parameters. Constructor failure is indicated by
57 returning undef and setting the "$ERROR" package variable in the
58 module's class to contain a relevant message (which you can also fetch
59 by calling "error()" as a class method).
60
61 e.g.
62
63 my $object = My::Module->new(
64 file => 'myfile.html',
65 msg => 'Hello World'
66 ) || die $My::Module::ERROR;
67
68 or:
69
70 my $object = My::Module->new({
71 file => 'myfile.html',
72 msg => 'Hello World',
73 }) || die My::Module->error();
74
75 The "new()" method handles the conversion of a list of arguments into a
76 hash array and calls the "init()" method to perform any initialisation.
77 In many cases, it is therefore sufficient to define a module like so:
78
79 package My::Module;
80 use Class::Base;
81 use base qw( Class::Base );
82
83 sub init {
84 my ($self, $config) = @_;
85 # copy some config items into $self
86 $self->params($config, qw( FOO BAR )) || return undef;
87 return $self;
88 }
89
90 # ...plus other application-specific methods
91
92 1;
93
94 Then you can go right ahead and use it like this:
95
96 use My::Module;
97
98 my $object = My::Module->new( FOO => 'the foo value',
99 BAR => 'the bar value' )
100 || die $My::Module::ERROR;
101
102 Despite its limitations, Class::Base can be a surprisingly useful module
103 to have lying around for those times where you just want to create a
104 regular object based on a blessed hash reference and don't want to worry
105 too much about duplicating the same old code to bless a hash, define
106 configuration values, provide an error reporting mechanism, and so on.
107 Simply derive your module from "Class::Base" and leave it to worry about
108 most of the detail. And don't forget, you can always redefine your own
109 "new()", "error()", or other method, if you don't like the way the
110 Class::Base version works.
111
112 Subclassing Class::Base
113
114 This module is what object-oriented afficionados would describe as an
115 "abstract base class". That means that it's not designed to be used as a
116 stand-alone module, rather as something from which you derive your own
117 modules. Like this:
118
119 package My::Funky::Module
120 use base qw( Class::Base );
121
122 You can then use it like this:
123
124 use My::Funky::Module;
125
126 my $module = My::Funky::Module->new();
127
128 Construction and Initialisation Methods
129
130 If you want to apply any per-object initialisation, then simply write an
131 "init()" method. This gets called by the "new()" method which passes a
132 reference to a hash reference of configuration options.
133
134 sub init {
135 my ($self, $config) = @_;
136
137 ...
138
139 return $self;
140 }
141
142 When you create new objects using the "new()" method you can either pass
143 a hash reference or list of named arguments. The "new()" method does the
144 right thing to fold named arguments into a hash reference for passing to
145 the "init()" method. Thus, the following are equivalent:
146
147 # hash reference
148 my $module = My::Funky::Module->new({
149 foo => 'bar',
150 wiz => 'waz',
151 });
152
153 # list of named arguments (no enclosing '{' ... '}')
154 my $module = My::Funky::Module->new(
155 foo => 'bar',
156 wiz => 'waz'
157 );
158
159 Within the "init()" method, you can either handle the configuration
160 yourself:
161
162 sub init {
163 my ($self, $config) = @_;
164
165 $self->{ file } = $config->{ file }
166 || return $self->error('no file specified');
167
168 return $self;
169 }
170
171 or you can call the "params()" method to do it for you:
172
173 sub init {
174 my ($self, $config) = @_;
175
176 $self->params($config, 'file')
177 || return $self->error('no file specified');
178
179 return $self;
180 }
181
182 Error Handling
183
184 The "init()" method should return $self to indicate success or undef to
185 indicate a failure. You can use the "error()" method to report an error
186 within the "init()" method. The "error()" method returns undef, so you
187 can use it like this:
188
189 sub init {
190 my ($self, $config) = @_;
191
192 # let's make 'foobar' a mandatory argument
193 $self->{ foobar } = $config->{ foobar }
194 || return $self->error("no foobar argument");
195
196 return $self;
197 }
198
199 When you create objects of this class via "new()", you should now check
200 the return value. If undef is returned then the error message can be
201 retrieved by calling "error()" as a class method.
202
203 my $module = My::Funky::Module->new()
204 || die My::Funky::Module->error();
205
206 Alternately, you can inspect the "$ERROR" package variable which will
207 contain the same error message.
208
209 my $module = My::Funky::Module->new()
210 || die $My::Funky::Module::ERROR;
211
212 Of course, being a conscientious Perl programmer, you will want to be
213 sure that the "$ERROR" package variable is correctly defined.
214
215 package My::Funky::Module
216 use base qw( Class::Base );
217
218 our $ERROR;
219
220 You can also call "error()" as an object method. If you pass an argument
221 then it will be used to set the internal error message for the object
222 and return undef. Typically this is used within the module methods to
223 report errors.
224
225 sub another_method {
226 my $self = shift;
227
228 ...
229
230 # set the object error
231 return $self->error('something bad happened');
232 }
233
234 If you don't pass an argument then the "error()" method returns the
235 current error value. Typically this is called from outside the object to
236 determine its status. For example:
237
238 my $object = My::Funky::Module->new()
239 || die My::Funky::Module->error();
240
241 $object->another_method()
242 || die $object->error();
243
244 Debugging Methods
245
246 The module implements two methods to assist in writing debugging code:
247 debug() and debugging(). Debugging can be enabled on a per-object or
248 per-class basis, or as a combination of the two.
249
250 When creating an object, you can set the "DEBUG" flag (or lower case
251 "debug" if you prefer) to enable or disable debugging for that one
252 object.
253
254 my $object = My::Funky::Module->new( debug => 1 )
255 || die My::Funky::Module->error();
256
257 my $object = My::Funky::Module->new( DEBUG => 1 )
258 || die My::Funky::Module->error();
259
260 If you don't explicitly specify a debugging flag then it assumes the
261 value of the "$DEBUG" package variable in your derived class or 0 if
262 that isn't defined.
263
264 You can also switch debugging on or off via the "debugging()" method.
265
266 $object->debugging(0); # debug off
267 $object->debugging(1); # debug on
268
269 The "debug()" method examines the internal debugging flag (the "_DEBUG"
270 member within the "$self" hash) and if it finds it set to any true value
271 then it prints to STDERR all the arguments passed to it. The output is
272 prefixed by a tag containing the class name of the object in square
273 brackets (but see the "id()" method below for details on how to change
274 that value).
275
276 For example, calling the method as:
277
278 $object->debug('foo', 'bar');
279
280 prints the following output to STDERR:
281
282 [My::Funky::Module] foobar
283
284 When called as class methods, "debug()" and "debugging()" instead use
285 the "$DEBUG" package variable in the derived class as a flag to control
286 debugging. This variable also defines the default "DEBUG" flag for any
287 objects subsequently created via the new() method.
288
289 package My::Funky::Module
290 use base qw( Class::Base );
291
292 our $ERROR;
293 our $DEBUG = 0 unless defined $DEBUG;
294
295 # some time later, in a module far, far away
296 package main;
297
298 # debugging off (by default)
299 my $object1 = My::Funky::Module->new();
300
301 # turn debugging on for My::Funky::Module objects
302 $My::Funky::Module::DEBUG = 1;
303
304 # alternate syntax
305 My::Funky::Module->debugging(1);
306
307 # debugging on (implicitly from $DEBUG package var)
308 my $object2 = My::Funky::Module->new();
309
310 # debugging off (explicit override)
311 my $object3 = My::Funky::Module->new(debug => 0);
312
313 If you call "debugging()" without any arguments then it returns the
314 value of the internal object flag or the package variable accordingly.
315
316 print "debugging is turned ", $object->debugging() ? 'on' : 'off';
317
318 METHODS
319 new()
320
321 Class constructor method which expects a reference to a hash array of
322 parameters or a list of "name => value" pairs which are automagically
323 folded into a hash reference. The method blesses a hash reference and
324 then calls the "init()" method, passing the reference to the hash array
325 of configuration parameters.
326
327 Returns a reference to an object on success or undef on error. In the
328 latter case, the "error()" method can be called as a class method, or
329 the "$ERROR" package variable (in the derived class' package) can be
330 inspected to return an appropriate error message.
331
332 my $object = My::Class->new( foo => 'bar' ) # params list
333 || die $My::Class::$ERROR; # package var
334
335 or
336
337 my $object = My::Class->new({ foo => 'bar' }) # params hashref
338 || die My::Class->error; # class method
339
340 init(\%config)
341
342 Object initialiser method which is called by the "new()" method, passing
343 a reference to a hash array of configuration parameters. The method may
344 be derived in a subclass to perform any initialisation required. It
345 should return "$self" on success, or "undef" on error, via a call to the
346 "error()" method.
347
348 package My::Module;
349 use base qw( Class::Base );
350
351 sub init {
352 my ($self, $config) = @_;
353
354 # let's make 'foobar' a mandatory argument
355 $self->{ foobar } = $config->{ foobar }
356 || return $self->error("no foobar argument");
357
358 return $self;
359 }
360
361 params($config, @keys)
362
363 The "params()" method accept a reference to a hash array as the first
364 argument containing configuration values such as those passed to the
365 "init()" method. The second argument can be a reference to a list of
366 parameter names or a reference to a hash array mapping parameter names
367 to default values. If the second argument is not a reference then all
368 the remaining arguments are taken as parameter names. Thus the method
369 can be called as follows:
370
371 sub init {
372 my ($self, $config) = @_;
373
374 # either...
375 $self->params($config, qw( foo bar ));
376
377 # or...
378 $self->params($config, [ qw( foo bar ) ]);
379
380 # or...
381 $self->params($config, { foo => 'default foo value',
382 bar => 'default bar value' } );
383
384 return $self;
385 }
386
387 The method looks for values in $config corresponding to the keys
388 specified and copies them, if defined, into $self.
389
390 Keys can be specified in UPPER CASE and the method will look for either
391 upper or lower case equivalents in the "$config" hash. Thus you can call
392 "params()" from "init()" like so:
393
394 sub init {
395 my ($self, $config) = @_;
396 $self->params($config, qw( FOO BAR ))
397 return $self;
398 }
399
400 but use either case for parameters passed to "new()":
401
402 my $object = My::Module->new( FOO => 'the foo value',
403 BAR => 'the bar value' )
404 || die My::Module->error();
405
406 my $object = My::Module->new( foo => 'the foo value',
407 bar => 'the bar value' )
408 || die My::Module->error();
409
410 Note however that the internal key within "$self" used to store the
411 value will be in the case provided in the call to "params()" (upper case
412 in this example). The method doesn't look for upper case equivalents
413 when they are specified in lower case.
414
415 When called in list context, the method returns a list of all the values
416 corresponding to the list of keys, some of which may be undefined
417 (allowing you to determine which values were successfully set if you
418 need to). When called in scalar context it returns a reference to the
419 same list.
420
421 clone()
422
423 The "clone()" method performs a simple shallow copy of the object hash
424 and creates a new object blessed into the same class. You may want to
425 provide your own "clone()" method to perform a more complex cloning
426 operation.
427
428 my $clone = $object->clone();
429
430 error($msg, ...)
431
432 General purpose method for getting and setting error messages. When
433 called as a class method, it returns the value of the "$ERROR" package
434 variable (in the derived class' package) if called without any
435 arguments, or sets the same variable when called with one or more
436 arguments. Multiple arguments are concatenated together.
437
438 # set error
439 My::Module->error('set the error string');
440 My::Module->error('set ', 'the ', 'error string');
441
442 # get error
443 print My::Module->error();
444 print $My::Module::ERROR;
445
446 When called as an object method, it operates on the "_ERROR" member of
447 the object, returning it when called without any arguments, or setting
448 it when called with arguments.
449
450 # set error
451 $object->error('set the error string');
452
453 # get error
454 print $object->error();
455
456 The method returns "undef" when called with arguments. This allows it to
457 be used within object methods as shown:
458
459 sub my_method {
460 my $self = shift;
461
462 # set error and return undef in one
463 return $self->error('bad, bad, error')
464 if $something_bad;
465 }
466
467 debug($msg, $msg, ...)
468
469 Prints all arguments to STDERR if the internal "_DEBUG" flag (when
470 called as an object method) or "$DEBUG" package variable (when called as
471 a class method) is set to a true value. Otherwise does nothing. The
472 output is prefixed by a string of the form "[Class::Name]" where the
473 name of the class is that returned by the "id()" method.
474
475 debugging($flag)
476
477 Used to get (no arguments) or set ($flag defined) the value of the
478 internal "_DEBUG" flag (when called as an object method) or "$DEBUG"
479 package variable (when called as a class method).
480
481 id($newid)
482
483 The "debug()" method calls this method to return an identifier for the
484 object for printing in the debugging message. By default it returns the
485 class name of the object (i.e. "ref $self"), but you can of course
486 subclass the method to return some other value. When called with an
487 argument it uses that value to set its internal "_ID" field which will
488 be returned by subsequent calls to "id()".
489
490 AUTHOR
491 Andy Wardley <[email protected]>
492
493 VERSION
494 This is version 0.03 of Class::Base.
495
496 HISTORY
497 This module began life as the Template::Base module distributed as part
498 of the Template Toolkit.
499
500 Thanks to Brian Moseley and Matt Sergeant for suggesting various
501 enhancments, some of which went into version 0.02.
502
503 COPYRIGHT
504 Copyright (C) 1996-2002 Andy Wardley. All Rights Reserved.
505
506 This module is free software; you can redistribute it and/or modify it
507 under the same terms as Perl itself.
508