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