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
50 practically every Perl project of any significant size. Or rather, I
51 would copy the module from the last project and perform a global search
52 and replace to change the names. Each time it got a little more
53 polished and eventually, I decided to Do The Right Thing and release it
54 as a 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
62 module's class to contain a relevant message (which you can also fetch
63 by 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
107 module to have lying around for those times where you just want to
108 create a regular object based on a blessed hash reference and don't
109 want to worry too much about duplicating the same old code to bless a
110 hash, define configuration values, provide an error reporting
111 mechanism, and so on. Simply derive your module from "Class::Base" and
112 leave it to worry about most of the detail. And don't forget, you can
113 always redefine your own "new()", "error()", or other method, if you
114 don't like the way the Class::Base version works.
115
116 Subclassing Class::Base
117 This module is what object-oriented afficionados would describe as an
118 "abstract base class". That means that it's not designed to be used as
119 a stand-alone module, rather as something from which you derive your
120 own modules. Like this:
121
122 package My::Funky::Module
123 use base qw( Class::Base );
124
125 You can then use it like this:
126
127 use My::Funky::Module;
128
129 my $module = My::Funky::Module->new();
130
131 Construction and Initialisation Methods
132 If you want to apply any per-object initialisation, then simply write
133 an "init()" method. This gets called by the "new()" method which
134 passes a reference to a hash reference of configuration options.
135
136 sub init {
137 my ($self, $config) = @_;
138
139 ...
140
141 return $self;
142 }
143
144 When you create new objects using the "new()" method you can either
145 pass a hash reference or list of named arguments. The "new()" method
146 does the right thing to fold named arguments into a hash reference for
147 passing to the "init()" method. Thus, the following are equivalent:
148
149 # hash reference
150 my $module = My::Funky::Module->new({
151 foo => 'bar',
152 wiz => 'waz',
153 });
154
155 # list of named arguments (no enclosing '{' ... '}')
156 my $module = My::Funky::Module->new(
157 foo => 'bar',
158 wiz => 'waz'
159 );
160
161 Within the "init()" method, you can either handle the configuration
162 yourself:
163
164 sub init {
165 my ($self, $config) = @_;
166
167 $self->{ file } = $config->{ file }
168 || return $self->error('no file specified');
169
170 return $self;
171 }
172
173 or you can call the "params()" method to do it for you:
174
175 sub init {
176 my ($self, $config) = @_;
177
178 $self->params($config, 'file')
179 || return $self->error('no file specified');
180
181 return $self;
182 }
183
184 Error Handling
185 The "init()" method should return $self to indicate success or undef to
186 indicate a failure. You can use the "error()" method to report an
187 error within the "init()" method. The "error()" method returns undef,
188 so you can use it like this:
189
190 sub init {
191 my ($self, $config) = @_;
192
193 # let's make 'foobar' a mandatory argument
194 $self->{ foobar } = $config->{ foobar }
195 || return $self->error("no foobar argument");
196
197 return $self;
198 }
199
200 When you create objects of this class via "new()", you should now check
201 the return value. If undef is returned then the error message can be
202 retrieved by calling "error()" as a class method.
203
204 my $module = My::Funky::Module->new()
205 || die My::Funky::Module->error();
206
207 Alternately, you can inspect the $ERROR package variable which will
208 contain the same error message.
209
210 my $module = My::Funky::Module->new()
211 || die $My::Funky::Module::ERROR;
212
213 Of course, being a conscientious Perl programmer, you will want to be
214 sure that the $ERROR package variable is correctly defined.
215
216 package My::Funky::Module
217 use base qw( Class::Base );
218
219 our $ERROR;
220
221 You can also call "error()" as an object method. If you pass an
222 argument then it will be used to set the internal error message for the
223 object and return undef. Typically this is used within the module
224 methods to report errors.
225
226 sub another_method {
227 my $self = shift;
228
229 ...
230
231 # set the object error
232 return $self->error('something bad happened');
233 }
234
235 If you don't pass an argument then the "error()" method returns the
236 current error value. Typically this is called from outside the object
237 to determine its status. For example:
238
239 my $object = My::Funky::Module->new()
240 || die My::Funky::Module->error();
241
242 $object->another_method()
243 || die $object->error();
244
245 Debugging Methods
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 that
262 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
319 new()
320 Class constructor method which expects a reference to a hash array of
321 parameters or a list of "name => value" pairs which are automagically
322 folded into a hash reference. The method blesses a hash reference and
323 then calls the "init()" method, passing the reference to the hash array
324 of configuration parameters.
325
326 Returns a reference to an object on success or undef on error. In the
327 latter case, the "error()" method can be called as a class method, or
328 the $ERROR package variable (in the derived class' package) can be
329 inspected to return an appropriate error message.
330
331 my $object = My::Class->new( foo => 'bar' ) # params list
332 || die $My::Class::$ERROR; # package var
333
334 or
335
336 my $object = My::Class->new({ foo => 'bar' }) # params hashref
337 || die My::Class->error; # class method
338
339 init(\%config)
340 Object initialiser method which is called by the "new()" method,
341 passing a reference to a hash array of configuration parameters. The
342 method may be derived in a subclass to perform any initialisation
343 required. It should return $self on success, or "undef" on error, via
344 a call to the "error()" method.
345
346 package My::Module;
347 use base qw( Class::Base );
348
349 sub init {
350 my ($self, $config) = @_;
351
352 # let's make 'foobar' a mandatory argument
353 $self->{ foobar } = $config->{ foobar }
354 || return $self->error("no foobar argument");
355
356 return $self;
357 }
358
359 params($config, @keys)
360 The "params()" method accept a reference to a hash array as the first
361 argument containing configuration values such as those passed to the
362 "init()" method. The second argument can be a reference to a list of
363 parameter names or a reference to a hash array mapping parameter names
364 to default values. If the second argument is not a reference then all
365 the remaining arguments are taken as parameter names. Thus the method
366 can be called as follows:
367
368 sub init {
369 my ($self, $config) = @_;
370
371 # either...
372 $self->params($config, qw( foo bar ));
373
374 # or...
375 $self->params($config, [ qw( foo bar ) ]);
376
377 # or...
378 $self->params($config, { foo => 'default foo value',
379 bar => 'default bar value' } );
380
381 return $self;
382 }
383
384 The method looks for values in $config corresponding to the keys
385 specified and copies them, if defined, into $self.
386
387 Keys can be specified in UPPER CASE and the method will look for either
388 upper or lower case equivalents in the $config hash. Thus you can call
389 "params()" from "init()" like so:
390
391 sub init {
392 my ($self, $config) = @_;
393 $self->params($config, qw( FOO BAR ))
394 return $self;
395 }
396
397 but use either case for parameters passed to "new()":
398
399 my $object = My::Module->new( FOO => 'the foo value',
400 BAR => 'the bar value' )
401 || die My::Module->error();
402
403 my $object = My::Module->new( foo => 'the foo value',
404 bar => 'the bar value' )
405 || die My::Module->error();
406
407 Note however that the internal key within $self used to store the value
408 will be in the case provided in the call to "params()" (upper case in
409 this example). The method doesn't look for upper case equivalents when
410 they are specified in lower case.
411
412 When called in list context, the method returns a list of all the
413 values corresponding to the list of keys, some of which may be
414 undefined (allowing you to determine which values were successfully set
415 if you need to). When called in scalar context it returns a reference
416 to the same list.
417
418 clone()
419 The "clone()" method performs a simple shallow copy of the object hash
420 and creates a new object blessed into the same class. You may want to
421 provide your own "clone()" method to perform a more complex cloning
422 operation.
423
424 my $clone = $object->clone();
425
426 error($msg, ...)
427 General purpose method for getting and setting error messages. When
428 called as a class method, it returns the value of the $ERROR package
429 variable (in the derived class' package) if called without any
430 arguments, or sets the same variable when called with one or more
431 arguments. Multiple arguments are concatenated together.
432
433 # set error
434 My::Module->error('set the error string');
435 My::Module->error('set ', 'the ', 'error string');
436
437 # get error
438 print My::Module->error();
439 print $My::Module::ERROR;
440
441 When called as an object method, it operates on the "_ERROR" member of
442 the object, returning it when called without any arguments, or setting
443 it when called with arguments.
444
445 # set error
446 $object->error('set the error string');
447
448 # get error
449 print $object->error();
450
451 The method returns "undef" when called with arguments. This allows it
452 to be used within object methods as shown:
453
454 sub my_method {
455 my $self = shift;
456
457 # set error and return undef in one
458 return $self->error('bad, bad, error')
459 if $something_bad;
460 }
461
462 debug($msg, $msg, ...)
463 Prints all arguments to STDERR if the internal "_DEBUG" flag (when
464 called as an object method) or $DEBUG package variable (when called as
465 a class method) is set to a true value. Otherwise does nothing. The
466 output is prefixed by a string of the form "[Class::Name]" where the
467 name of the class is that returned by the "id()" method.
468
469 debugging($flag)
470 Used to get (no arguments) or set ($flag defined) the value of the
471 internal "_DEBUG" flag (when called as an object method) or $DEBUG
472 package variable (when called as a class method).
473
474 id($newid)
475 The "debug()" method calls this method to return an identifier for the
476 object for printing in the debugging message. By default it returns
477 the class name of the object (i.e. "ref $self"), but you can of course
478 subclass the method to return some other value. When called with an
479 argument it uses that value to set its internal "_ID" field which will
480 be returned by subsequent calls to "id()".
481
483 Andy Wardley <abw@kfs.org>
484
486 This is version 0.03 of Class::Base.
487
489 This module began life as the Template::Base module distributed as part
490 of the Template Toolkit.
491
492 Thanks to Brian Moseley and Matt Sergeant for suggesting various
493 enhancments, some of which went into version 0.02.
494
496 Copyright (C) 1996-2002 Andy Wardley. All Rights Reserved.
497
498 This module is free software; you can redistribute it and/or modify it
499 under the same terms as Perl itself.
500
501
502
503perl v5.12.0 2002-04-05 Class::Base(3)