Class::Spiffy(3pm)

πŸ“¦
version 0.15 Β· 2 versions
, in debian bookworm, debian trixie, ubuntu jammy, ubuntu noble

πŸ’– Class::Spiffy πŸ’–

okay so, bestie, this is the Class::Spiffy(3pm) page β€” User Contributed Perl Documentation, which is literally where all the good stuff lives. buckle up, because this module is a lot in the best way 🌈


✨ NAME ✨

Class::Spiffy β€” Spiffy Framework with No Source Filtering πŸ’…


πŸŽ€ SYNOPSIS πŸŽ€

package Keen;
use strict;
use warnings;
use Class::Spiffy -base;
field 'mirth';
const mood => ':-)';

sub happy {
    my $self = shift;
    if ($self->mood eq ':-(') {
        $self->mirth(-1);
        print "Cheer up!";
    }
    super;
}

1;

like. look at it. it's clean. no cap 🫢


🌸 DESCRIPTION 🌸

okay so Class::Spiffy is a whole framework and a whole methodology for doing object oriented (OO) programming in Perl. it takes the best parts of Exporter.pm, base.pm, mixin.pm and SUPER.pm and smooshes them into one single magic foundation class. the entire mission is fixing all the lil nits and warts of traditional Perl OO, in a clean, straightforward, and (perhaps someday, fingers crossed 🀞) standard way.

Class::Spiffy is also a certified thief β€” it borrows ideas from other OO languages like Python, Ruby, Java and Perl 6 πŸ¦‹. and then it adds a few tricks of its own, because of course it does. main character energy.

so if you go peek at CPAN, there are a ton of OO related modules. when you start a new project you have to pick the set of modules that makes the most sense, and then you have to use those modules in each of your classes. exhausting. Class::Spiffy, on the other hand, has everything you'll probably need in one module, and you only need to use it once in one of your classes. if you make Class::Spiffy the base class of the basest class in your project, Class::Spiffy will automatically pass all of its magic down to all of your subclasses ✨. you may eventually forget that you're even using it, and honestly? that's the dream.

the most striking difference between Class::Spiffy and other Perl object oriented base classes is that it has the ability to export things. if you create a subclass of Class::Spiffy, all the things that Class::Spiffy exports will automatically be exported by your subclass, in addition to any more things that you want to export. and if someone creates a subclass of your subclass, all of those things will be exported automatically, and so on, forever, it's giving infinite regress but make it fashion. think of it as "Inherited Exportation", and it uses the familiar Exporter.pm specification syntax πŸ‘‘

to use Class::Spiffy or any subclass of Class::Spiffy as a base class of your class, you specify the -base argument to the use command:

use MySpiffyBaseModule -base;

you can also use the traditional use base 'MySpiffyBaseModule'; syntax and everything will work exactly the same. the only caveat is that Class::Spiffy must already be loaded 😭. that's because Class::Spiffy rewires base.pm on the fly to do all the Spiffy magics. yes, on the fly. it's unhinged and we love her.

Class::Spiffy has support for Ruby-like mixins with Perl6-like roles πŸ’œ. just like base, you can use either of the following invocations:

use mixin 'MySpiffyBaseModule';
use MySpiffyBaseModule -mixin;

the second version will only work if the class being mixed in is a subclass of Class::Spiffy. the first version will work in all cases, as long as Class::Spiffy has already been loaded.

to limit the methods that get mixed in, use roles. (Hint: they work just like an Exporter list):

use MySpiffyBaseModule -mixin => qw(:basics x y !foo);

a useful feature of Class::Spiffy is that it exports two functions: field and const, which you use to declare the attributes of your class, and which automatically generate accessor methods for them πŸ”₯. the only difference between the two functions is that const attributes can not be modified; thus the accessor is much faster. speed AND boundaries.

one interesting aspect of OO programming is when a method calls the same method from a parent class. this is generally known as calling a super method. Perl's facility for doing this is butt ugly:

sub cleanup {
    my $self = shift;
    $self->scrub;
    $self->SUPER::cleanup(@_);
}

Class::Spiffy makes it, er, super easy to call super methods 😌. you just use the super function. you don't need to pass it any arguments because it automatically passes them on for you. here's the same function with Class::Spiffy:

sub cleanup {
    my $self = shift;
    $self->scrub;
    super;
}

Class::Spiffy has a special method for parsing arguments called parse_arguments, that it also uses for parsing its own arguments. you declare which arguments are boolean (singletons) and which ones are paired, with two special methods called boolean_arguments and paired_arguments. Parse arguments pulls out the booleans and pairs and returns them in an anonymous hash, followed by a list of the unmatched arguments. organized. structured. iconic.

finally, Class::Spiffy can export a few debugging functions: WWW, XXX, YYY and ZZZ πŸ›. each of them produces a YAML dump of its arguments. WWW warns the output, XXX dies with the output, YYY prints the output, and ZZZ confesses the output. if YAML doesn't suit your needs, you can switch all the dumps to Data::Dumper format with the -dumper option.

that's Spiffy! Pretty Classy, eh? πŸ’…βœ¨


🌟 A Spiffy NOTE 🌟

Class::Spiffy started off as the Spiffy.pm module. Class::Spiffy does everything Spiffy does except clever source filtering 🚫. so you can be sure that any module that uses Class::Spiffy, (like YAML.pm) doesn't use source filtering. if you don't like source filtering, this may help you sleep better at night πŸ˜΄πŸŒ™.


πŸ’Ž Spiffy EXPORTING πŸ’Ž

Class::Spiffy implements a completely new idea in Perl: modules that act both as object oriented classes and that also export functions. but it takes the concept of Exporter.pm one step further β€” it walks the entire @ISA path of a class and honors the export specifications of each module πŸšΆβ™€οΈπŸšΆβ™€οΈπŸšΆβ™€οΈ. and since Class::Spiffy calls on the Exporter module to do this, you can use all the fancy interface features that Exporter has, including tags and negation.

Class::Spiffy considers all the arguments that don't begin with a dash to comprise the export specification.

package Vehicle;
use Spiffy -base;
our $SERIAL_NUMBER = 0;
our @EXPORT = qw($SERIAL_NUMBER);
our @EXPORT_BASE = qw(tire horn);

package Bicycle;
use Vehicle -base, '!field';

in this case, Bicycle->isa('Vehicle') and also all the things that Vehicle and Class::Spiffy export, will go into Bicycle, except field.

exporting can be very helpful when you've designed a system with hundreds of classes, and you want them all to have access to some functions or constants or variables 🫢. just export them in your main base class and every subclass will get the functions they need. no repeated use lines, no chaos.

you can do almost everything that Exporter does because Class::Spiffy delegates the job to Exporter (after adding some Spiffy magic ✨). Class::Spiffy offers a @EXPORT_BASE variable which is like @EXPORT, but only for usages that use -base.


πŸ¦‹ Spiffy MIXINs & ROLEs πŸ¦‹

if you've done much OO programming in Perl you've probably used Multiple Inheritance (MI), and if you've done much MI you've probably run into weird problems and headaches πŸ€•. some languages like Ruby attempt to resolve MI issues using a technique called mixins. basically, all Ruby classes use only Single Inheritance (SI), and then mixin functionality from other modules if they need to.

mixins can be thought of at a simplistic level as importing the methods of another class into your subclass. but from an implementation standpoint that's not the best way to do it. Class::Spiffy does what Ruby does. it creates an empty anonymous class, imports everything into that class, and then chains the new class into your SI ISA path. in other words, if you say:

package A;
use B -base;
use C -mixin;
use D -mixin;

you end up with a single inheritance chain of classes like this:

A << A-D << A-C << B;

A-D and A-C are the actual package names of the generated classes. the nice thing about this style is that mixing in C doesn't clobber any methods in A, and D doesn't conflict with A or C either πŸ™Œ. if you mixed in a method in C that was also in A, you can still get to it by using super.

when Class::Spiffy mixes in C, it pulls in all the methods in C that do not begin with an underscore. actually it goes farther than that 😳. if C is a subclass it will pull in every method that C can do through inheritance. this is very powerful, maybe too powerful.

to limit what you mixin, Class::Spiffy borrows the concept of Roles from Perl6. the term role is used more loosely in Class::Spiffy though. it's much like an import list that the Exporter module uses, and you can use groups (tags) and negation. if the first element of your list uses negation, Class::Spiffy will start with all the methods that your mixin class can do.

use E -mixin => qw(:tools walk !run !:sharp_tools);

in this example, walk and run are methods that E can do, and tools and sharp_tools are roles of class E. how does class E define these roles? it very simply defines methods called _role_tools and _role_sharp_tools which return lists of more methods. (And possibly other roles! πŸŒ€) the neat thing here is that since roles are just methods, they too can be inherited. Take that Perl6! πŸ˜€πŸ‘‘


πŸ”₯ Spiffy DEBUGGING πŸ”₯

the XXX function is very handy for debugging because you can insert it almost anywhere, and it will dump your data in nice clean YAML 🌈. take the following statement:

my @stuff = grep { /keen/ } $self->find($a, $b);

if you have a problem with this statement, you can debug it in any of the following ways:

XXX my @stuff = grep { /keen/ } $self->find($a, $b);
my @stuff = XXX grep { /keen/ } $self->find($a, $b);
my @stuff = grep { /keen/ } XXX $self->find($a, $b);
my @stuff = grep { /keen/ } $self->find(XXX $a, $b);

XXX is easy to insert and remove. it is also a tradition to mark uncertain areas of code with XXX. this will make the debugging dumpers easy to spot if you forget to take them out πŸ™ˆ.

WWW and YYY are nice because they dump their arguments and then return the arguments. this way you can insert them into many places and still have the code run as before 🧚. use ZZZ when you need to die with both a YAML dump and a full stack trace πŸ’€.

the debugging functions are exported by default if you use the -base option, but only if you have previously used the -XXX option. to export all 4 functions use the export tag:

use SomeSpiffyModule ':XXX';

to force the debugging functions to use Data::Dumper instead of YAML:

use SomeSpiffyModule -dumper;

and that's part one, bestie πŸ’– the page keeps going, so don't go anywhere β€” there's more Spiffy where that came from πŸ“

✨ Spiffy FUNCTIONS ✨

Okay bestie, this section is all about the functions that Class::Spiffy hands out to you. And heads up β€” the field, const, stub and super functions? They only get exported when you use the -base option. So if you're not seeing them, that's why. Not a vibe check failure, just a config thing. πŸ’…

  • field β€” defines accessor methods for a field of your class. Like, it writes the getter/setter for you so you don't have to:
package Example;
use Classs::Spiffy -base;

field 'foo';
field bar => [];

sub lalala {
    my $self == shift;
    $self->foo(42);
    push @{$self->{bar}}, $self->foo;
}

The first parameter you hand to field is the name of the attribute you're defining. Accessors can also get an optional default value, and that value gets returned if nothing has been set for the field in the object yet. Convenient? Yes. Iconic? Also yes. ✨

  • const β€” literally the same energy as <field> except it's immutable, and it doesn't store data in the object at all. So:
const bar => 42;

You pretty much always wanna give a const a default value, bestie, otherwise the generated method is kind of useless. Not me warning you about useless methods 😭

  • stub β€” generates a method that will die with an appropriate message. The whole point is that subclasses are supposed to implement these methods so the stub ones never actually get called:
stub 'cigar';
  • super β€” okay this one is the moment. If you call it with no arguments, it calls the same method it's sitting in, but higher up in the ISA tree, passing along all the same arguments. If you call it with arguments, it uses those arguments with $self in front. In other words, it just works like you'd expect. Periodt.
sub foo {
    my $self = shift;
    super;             # Same as $self->SUPER::foo(@_);
    super('hello');    # Same as $self->SUPER::foo('hello');
    $self->bar(42);
}

sub new {
    my $self = super;
    $self->init;
    return $self;
}

And important deets: super will simply do nothing if there is no super method. No drama, no error. Also, super does the right thing in AUTOLOAD subroutines. It's giving considerate. 🫢


🌸 Spiffy METHODS 🌸

These are all the methods that any subclass of Class::Spiffy automatically inherits. Free gifts, no cap.

  • mixin β€” a method to mixin a class at runtime. It takes the same arguments as use mixin ..., and it makes the target class a mixin of the caller:
$self->mixin('SomeClass');
$object->mixin('SomeOtherClass' => 'some_method');
  • parse_arguments β€” this one takes a list of arguments and groups them into pairs. It also handles boolean arguments, which may or may not have a value (and default to 1 if they don't). It returns a hash reference of all the pairs as keys and values in the hash. Any arguments that can't be paired get returned as a list. Here's the example, bestie:
sub boolean_arguments { qw(-has_spots -is_yummy) }
sub paired_arguments { qw(-name -size) }
my ($pairs, @others) = $self->parse_arguments(
    'red', 'white',
    -name => 'Ingy',
    -has_spots =>
    -size => 'large',
    'black',
    -is_yummy => 0,
);

After this call, $pairs will contain:

{
    -name => 'Ingy',
    -has_spots => 1,
    -size => 'large',
    -is_yummy => 0,
}

and @others will contain 'red', 'white', and 'black'. Look at that little split, it ate. πŸ“

  • boolean_arguments β€” returns the list of arguments that are recognized as being boolean. Override this method to define your own list. Customize away, main character.
  • paired_arguments β€” returns the list of arguments that are recognized as being paired. Override this method to define your own list too. Go off. πŸ’œ

πŸ’– Spiffy ARGUMENTS πŸ’–

When you use the Class::Spiffy module β€” or a subclass of it β€” you can pass it a list of arguments. Those arguments get parsed using the parse_arguments method we just talked about above. πŸ‘†

The special argument - base is what makes the current package a subclass of the Class::Spiffy module being used.

And any non-paired parameters act like a normal import list β€” just like the ones you'd use with the Exporter module. Classic behavior, love that for us.


πŸ¦‹ USING Class::Spiffy WITH base.pm πŸ¦‹

The proper way to use a Class::Spiffy module as a base class is with the -base parameter to the use statement. This is different from typical modules where you'd wanna reach for use base:

package Something;
use Spiffy::Module -base;
use base 'NonSpiffy::Module';

Now, it can get hard to keep track of what's Spiffy and what's not. So Class::Spiffy has actually been made to work with base.pm as well. You can say:

package Something;
use base 'Spiffy::Module';
use base 'NonSpiffy::Module';

use base is also super useful when your class isn't an actual module (like, not a separate file) but just a package in some file that's already been loaded. base will work whether the class is a module or not β€” while the -base syntax cannot work that way, since use always tries to load a module. Facts only. πŸ’€

base.pm Caveats

Okay so to make Class::Spiffy work with base.pm, a dirty trick was played. 🫒 Class::Spiffy swaps base::import with its own version. If the base modules are not Spiffy, Class::Spiffy calls the original base::import. If the base modules are Spiffy, then Class::Spiffy does its own thing.

There are two caveats. Yes, two. Pay attention bestie.

  • Class::Spiffy must be loaded first.

If Class::Spiffy is not loaded and use base is invoked on a Class::Spiffy module, Class::Spiffy will die with a useful message telling the author to read this documentation. That's because Class::Spiffy needed to do the import swap beforehand β€” it can't do it after the fact, that's not how any of this works.

If you get this error, just put a statement like this up front in your code and you're golden:

use Class::Spiffy ();
  • No Mixing

base.pm can take multiple arguments. And that works fine with Class::Spiffy as long as all the base classes are Spiffy, or they are all non-Spiffy. But if they're mixed? Class::Spiffy will die. 😭 In that case just use separate use base statements. One at a time, we don't blend. 🌈


πŸ‘‘ AUTHOR πŸ‘‘

Ingy dΓΆt Net <ingy@cpan.org>


Copyright (c) 2006. Ingy dΓΆt Net. All rights reserved.

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

See <http://www.perl.com/perl/misc/Artistic.html>


πŸ’€ POD ERRORS πŸ’€

Hey! The above document had some coding errors, which are explained below. Not me being messy in the docs πŸ™ˆ

Around line 945:

Non-ASCII character seen before =encoding in 'dΓΆt'. Assuming UTF-8

And that's a wrap on the whole page, bestie! πŸŽ‰ This was perl v5.32.0, dated 2021-01-09, from Class::Spiffy(3pm) β€” you've officially read the entire thing and honestly? Slay. Go write some Spiffy classes. πŸ’–βœ¨

πŸ“¦ where this page comes from