Class::Base(3pm)

πŸ“¦
version 0.09 Β· 4 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

🌸 NAME 🌸

okay so bestie, welcome to Class::Base(3pm) β€” it's part of the User Contributed Perl Documentation, and it's literally a useful base class for deriving other modules. no cap. πŸ’–

⭐ VERSION ⭐

this is version 0.09, periodt ✨

πŸŽ€ SYNOPSIS πŸŽ€

bestie, here's the whole group-chat demo in code, exactly as it goes:

package My::Funky::Module;
use base qw( Class::Base );

# custom initialiser method
sub init {
    my ($self, $config) = @_;

    # copy various params into $self
    $self->params($config, qw( FOO BAR BAZ ))
        || return undef;

    # to indicate a failure
    return $self->error('bad constructor!')
        if $something_bad;

    # or to indicate general happiness and well-being
    return $self;
}

package main;

# new() constructor folds args into hash and calls init()
my $object = My::Funky::Module->new( foo => 'bar', ... )
      || die My::Funky::Module->error();

# error() class/object method to get/set errors
$object->error('something has gone wrong');
print $object->error();

# debugging() method (de-)activates the debug() method
$object->debugging(1);

# debug() prints to STDERR if debugging enabled
$object->debug('The ', $animal, ' sat on the ', $place);

πŸ¦‹ DESCRIPTION πŸ¦‹

okay so first thing: please consider using Badger::Base instead β€” it's the successor of this module. iykyk. πŸ’…

this module implements a simple base class from which other modules can be derived, so they inherit a bunch of useful methods like new(), init(), params(), clone(), error() and debug(). it's giving object-oriented starter pack ✨

for a number of years, the author was like, I found myself re-writing this module for practically every Perl project of any significant size. or rather, I would copy the module from the last project and perform a global search and replace to change the names. each time it got a little more polished, and eventually, I decided to Do The Right Thing and release it as a module in it's own right. (yes, "it's" not "its" β€” we keep it exactly, bestie πŸ’€)

it doesn't pretend to be an all-encompassing solution for every kind of object creation problem you might encounter. in fact, it only supports blessed hash references that are created using the popular, but by no means universal, convention of calling new() with a list or reference to a hash array of named parameters. constructor failure is indicated by returning undef and setting the $ERROR package variable in the module's class to contain a relevant message β€” which you can also fetch by calling error() as a class method. no cap.

e.g.

my $object = My::Module->new(
    file => 'myfile.html',
    msg  => 'Hello World'
) || die $My::Module::ERROR;

or:

my $object = My::Module->new({
    file => 'myfile.html',
    msg  => 'Hello World',
}) || die My::Module->error();

the new() method handles the conversion of a list of arguments into a hash array and calls the init() method to perform any initialisation. in many cases, it is therefore sufficient to define a module like so:

package My::Module;
use Class::Base;
use base qw( Class::Base );

sub init {
    my ($self, $config) = @_;
    # copy some config items into $self
    $self->params($config, qw( FOO BAR )) || return undef;
    return $self;
}

# ...plus other application-specific methods

1;

then you can go right ahead and use it like this:

use My::Module;

my $object = My::Module->new( FOO => 'the foo value',
                              BAR => 'the bar value' )
    || die $My::Module::ERROR;

despite its limitations, Class::Base can be a surprisingly useful module to have lying around for those times where you just want to create a regular object based on a blessed hash reference and don't want to worry too much about duplicating the same old code to bless a hash, define configuration values, provide an error reporting mechanism, and so on. simply derive your module from Class::Base and leave it to worry about most of the detail. and don't forget, you can always redefine your own new(), error(), or other method, if you don't like the way the Class::Base version works. iconic behavior πŸ’–

🧚 Subclassing Class::Base 🧚

this module is what object-oriented afficionados would describe as an "abstract base class". that means it's not designed to be used as a stand-alone module, rather as something from which you derive your own modules. like this:

package My::Funky::Module
use base qw( Class::Base );

you can then use it like this:

use My::Funky::Module;

my $module = My::Funky::Module->new();

πŸ› οΈ Construction and Initialisation Methods πŸ› οΈ

if you want to apply any per-object initialisation, then simply write an init() method. this gets called by the new() method which passes a reference to a hash reference of configuration options. (yes, "a reference to a hash reference" β€” that's what it says, bestie πŸ’€)

sub init {
    my ($self, $config) = @_;

    ...

    return $self;
}

when you create new objects using the new() method you can either pass a hash reference or list of named arguments. the new() method does the right thing to fold named arguments into a hash reference for passing to the init() method. thus, the following are equivalent:

# hash reference
my $module = My::Funky::Module->new({
    foo => 'bar',
    wiz => 'waz',
});

# list of named arguments (no enclosing '{' ... '}')
my $module = My::Funky::Module->new(
    foo => 'bar',
    wiz => 'waz'
);

within the init() method, you can either handle the configuration yourself:

sub init {
    my ($self, $config) = @_;

    $self->{ file } = $config->{ file }
        || return $self->error('no file specified');

    return $self;
}

or you can call the params() method to do it for you:

sub init {
    my ($self, $config) = @_;

    $self->params($config, 'file')
        || return $self->error('no file specified');

    return $self;
}

😭 Error Handling 😭

the init() method should return $self to indicate success or undef to indicate a failure. you can use the error() method to report an error within the init() method. the error() method returns undef, so you can use it like this:

sub init {
    my ($self, $config) = @_;

    # let's make 'foobar' a mandatory argument
    $self->{ foobar } = $config->{ foobar }
        || return $self->error("no foobar argument");

    return $self;
}

when you create objects of this class via new(), you should now check the return value. if undef is returned then the error message can be retrieved by calling error() as a class method.

my $module = My::Funky::Module->new()
      || die My::Funky::Module->error();

alternately, you can inspect the $ERROR package variable which will contain the same error message.

my $module = My::Funky::Module->new()
     || die $My::Funky::Module::ERROR;

of course, being a conscientious Perl programmer, you will want to be sure that the $ERROR package variable is correctly defined.

package My::Funky::Module
use base qw( Class::Base );

our $ERROR;

you can also call error() as an object method. if you pass an argument then it will be used to set the internal error message for the object and return undef. typically this is used within the module methods to report errors.

sub another_method {
    my $self = shift;

    ...

    # set the object error
    return $self->error('something bad happened');
}

if you don't pass an argument then the error() method returns the current error value. typically this is called from outside the object to determine its status. for example:

my $object = My::Funky::Module->new()
    || die My::Funky::Module->error();

$object->another_method()
    || die $object->error();

πŸ”₯ Debugging Methods πŸ”₯

the module implements two methods to assist in writing debugging code: debug() and debugging(). debugging can be enabled on a per-object or per-class basis, or as a combination of the two.

when creating an object, you can set the DEBUG flag (or lower case debug if you prefer) to enable or disable debugging for that one object.

my $object = My::Funky::Module->new( debug => 1 )
      || die My::Funky::Module->error();

my $object = My::Funky::Module->new( DEBUG => 1 )
      || die My::Funky::Module->error();

if you don't explicitly specify a debugging flag then it assumes the value of the $DEBUG package variable in your derived class or 0 if that isn't defined.

you can also switch debugging on or off via the debugging() method.

$object->debugging(0);      # debug off
$object->debugging(1);      # debug on

the debug() method examines the internal debugging flag (the _DEBUG member within the $self hash) and if it finds it set to any true value then it prints to STDERR all the arguments passed to it. the output is prefixed by a tag containing the class name of the object in square brackets (but see the id() method below for details on how to change that value).

for example, calling the method as:

$object->debug('foo', 'bar');

prints the following output to STDERR:

[My::Funky::Module] foobar

when called as class methods, debug() and debugging() instead use the $DEBUG package variable in the derived class as a flag to control debugging. this variable also defines the default DEBUG flag for any objects subsequently created via the new() method.

package My::Funky::Module
use base qw( Class::Base );

our $ERROR;
our $DEBUG = 0 unless defined $DEBUG;

# some time later, in a module far, far away
package main;

# debugging off (by default)
my $object1 = My::Funky::Module->new();

# turn debugging on for My::Funky::Module objects
$My::Funky::Module::DEBUG = 1;

# alternate syntax
My::Funky::Module->debugging(1);

# debugging on (implicitly from $DEBUG package var)
my $object2 = My::Funky::Module->new();

# debugging off (explicit override)
my $object3 = My::Funky::Module->new(debug => 0);

if you call debugging() without any arguments then it returns the value of the internal object flag or the package variable accordingly.

print "debugging is turned ", $object->debugging() ? 'on' : 'off';

✨ METHODS ✨

🫢 new()

Okay bestie, this is the class constructor β€” the moment where your object is literally born πŸ’–. It expects either a reference to a hash array of parameters, or just a straight-up list of name => value pairs, and it'll automagically fold that list into a hash reference for you (iconic behaviour, no cap). Then it blesses a hash reference and calls the init() method, handing it the reference to that hash array of configuration parameters.

It returns a reference to an object on success, or undef on error 😭. When it's the error girlie route, you can call the error() method as a class method, or peek at the $ERROR package variable (living in the derived class' package) to get yourself an appropriate error message.

    my $object = My::Class->new( foo => 'bar' )   # params list
         || die $My::Class::$ERROR;               # package var

or

    my $object = My::Class->new({ foo => 'bar' }) # params hashref
          || die My::Class->error;                # class method

🌸 init(%config)

This is the object initialiser β€” it gets called by new(), which passes along a reference to a hash array of configuration parameters. You're meant to derive this method in a subclass to do whatever initialisation you need, bestie ✨. It should return $self on success, or undef on error β€” and when it's an error, that happens via a call to the error() method.

    package My::Module;
    use base qw( Class::Base );

    sub init {
        my ($self, $config) = @_;

        # let's make 'foobar' a mandatory argument
        $self->{ foobar } = $config->{ foobar }
            || return $self->error("no foobar argument");

        return $self;
    }

πŸ¦‹ params($config, @keys)

The params() method takes a reference to a hash array as its first argument, stuffed with configuration values like the ones passed to init(). The second argument can be either a reference to a list of parameter names, or a reference to a hash array that maps parameter names to default values πŸ’…. And if that second argument isn't a reference at all? Then all the remaining arguments get taken as parameter names. So you can call it like this:

    sub init {
        my ($self, $config) = @_;

        # either...
        $self->params($config, qw( foo bar ));

        # or...
        $self->params($config, [ qw( foo bar ) ]);

        # or...
        $self->params($config, { foo => 'default foo value',
                                 bar => 'default bar value' } );

        return $self;
    }

The method hunts through $config for values matching the keys you specified, and copies them into $self if they're defined (if they're not defined, it doesn't, periodt).

Here's the cute part: keys can be specified in UPPER CASE and the method will look for either upper or lower case equivalents in the $config hash. So you can call params() from init() like so:

    sub init {
        my ($self, $config) = @_;
        $self->params($config, qw( FOO BAR ))
        return $self;
    }

but then use either case for the parameters you pass to new():

    my $object = My::Module->new( FOO => 'the foo value',
                                  BAR => 'the bar value' )
        || die My::Module->error();

    my $object = My::Module->new( foo => 'the foo value',
                                  bar => 'the bar value' )
        || die My::Module->error();
⚠️ Heads up though β€” the internal key inside $self used to store the value will be in the case provided in the call to params() (upper case in that example, iykyk). And the method does not look for upper case equivalents when they're specified in lower case. So don't come for it later, bestie πŸ’€.

When it's called in list context, the method returns a list of all the values corresponding to the list of keys β€” and yes, some of them may be undefined, which is honestly a feature: it lets you figure out which values were successfully set if you need to. When it's called in scalar context, it returns a reference to that same list. Slay.


πŸŽ€ clone()

The clone() method does a simple shallow copy of the object hash and creates a new object blessed into the same class. If you want something fancier, you may want to provide your own clone() method to perform a more complex cloning operation β€” go off, main character πŸ‘‘.

    my $clone = $object->clone();

πŸ’œ error($msg, ...)

Your general purpose method for getting and setting error messages. Two whole moods depending on how you call it:

When called as a class method, it returns the value of the $ERROR package variable (in the derived class' package) if you call it with no arguments β€” or sets that same variable when you call it with one or more arguments. Multiple arguments get concatenated together 🌈.

    # set error
    My::Module->error('set the error string');
    My::Module->error('set ', 'the ', 'error string');

    # get error
    print My::Module->error();
    print $My::Module::ERROR;

When called as an object method, it operates on the _ERROR member of the object β€” returning it when called with no arguments, or setting it when called with arguments.

    # set error
    $object->error('set the error string');

    # get error
    print $object->error();

And here's the iconic bit: the method returns undef when called with arguments. That's on purpose β€” it lets you use it inside object methods like this:

    sub my_method {
        my $self = shift;

        # set error and return undef in one
        return $self->error('bad, bad, error')
            if $something_bad;
    }

🧚 debug($msg, $msg, ...)

Prints all the arguments to STDERR if the internal _DEBUG flag (when called as an object method) or the $DEBUG package variable (when called as a class method) is set to a true value. Otherwise? It does nothing. Silence. Vibe check failed, no output πŸ’€. The output gets prefixed by a string of the form [Class::Name], where the class name is whatever the id() method returns.


🌈 debugging($flag)

Used to get (no arguments) or set ($flag defined) the value of the internal _DEBUG flag when called as an object method, or the $DEBUG package variable when called as a class method. Simple as that, bestie ✨.


⭐ id($newid)

The debug() method calls this one to get back an identifier for the object, so it has something to print in the debugging message. By default it returns the class name of the object (i.e. ref $self), but obviously you can subclass the method to return some other value β€” do your thing 🫢. And when you call it with an argument, it uses that value to set its internal _ID field, which will then be returned by all the subsequent calls to id().


πŸ“œ HISTORY

This module began life as the Template::Base module distributed as part of the Template Toolkit. Glow-up story fr fr ✨.

Big thanks to Brian Moseley and Matt Sergeant for suggesting various enhancements β€” some of which went into version 0.02 πŸ’–.

Version 0.04 was uploaded by Gabor Szabo.


πŸ‘‘ AUTHORS

  • Andy Wardley β€” <abw@kfs.org>
  • Gabor Szabo β€” <gabor@szabgab.com>
  • Yanick Champoux β€” <yanick@cpan.org>

This software is copyright (c) 2018, 2016, 2014, 2012 by Andy Wardley.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.


okay that's the whole page bestie, we ate and left no crumbs πŸ’… this was perl v5.36.0, dated 2023-01-22, and it's the Class::Base(3pm) manpage β€” go forth and subclass responsibly πŸŒΈπŸ¦‹πŸ’œ

πŸ“¦ where this page comes from