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