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;

DESCRIPTION

\*(L"Class::Spiffy\*(R" is a framework and methodology for doing object oriented (\s-1OO\s0) programming in Perl. Class::Spiffy combines the best parts of Exporter.pm, base.pm, mixin.pm and \s-1SUPER\s0.pm into one magic foundation class. It attempts to fix all the nits and warts of traditional Perl \s-1OO\s0, in a clean, straightforward and (perhaps someday) standard way.

Class::Spiffy borrows ideas from other \s-1OO\s0 languages like Python, Ruby, Java and Perl 6. It also adds a few tricks of its own.

If you take a look on \s-1CPAN\s0, there are a ton of \s-1OO\s0 related modules. When starting a new project, you need to pick the set of modules that makes most sense, and then you need to use those modules in each of your classes. 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 to all of your subclasses. You may eventually forget that you're even using it!

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. Think of it as \*(L"Inherited Exportation\*(R", 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 \*(C`-base\*(C' argument to the \*(C`use\*(C' command.

use MySpiffyBaseModule -base;

You can also use the traditional \*(C`use base 'MySpiffyBaseModule';\*(C' 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.

Class::Spiffy has support for Ruby-like mixins with Perl6-like roles. Just like \*(C`base\*(C' 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: \*(C`field\*(C' and \*(C`const\*(C' that can be used to declare the attributes of your class, and automatically generate accessor methods for them. The only difference between the two functions is that \*(C`const\*(C' attributes can not be modified; thus the accessor is much faster.

One interesting aspect of \s-1OO\s0 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 \*(C`super\*(C' 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 \*(C`parse_arguments\*(C', 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 \*(C`boolean_arguments\*(C' and \*(C`paired_arguments\*(C'. Parse arguments pulls out the booleans and pairs and returns them in an anonymous hash, followed by a list of the unmatched arguments.

Finally, Class::Spiffy can export a few debugging functions \*(C`WWW\*(C', \*(C`XXX\*(C', \*(C`YYY\*(C' and \*(C`ZZZ\*(C'. Each of them produces a \s-1YAML\s0 dump of its arguments. \s-1WWW\s0 warns the output, \s-1XXX\s0 dies with the output, \s-1YYY\s0 prints the output, and \s-1ZZZ\s0 confesses the output. If \s-1YAML\s0 doesn't suit your needs, you can switch all the dumps to Data::Dumper format with the \*(C`- dumper\*(C' 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 \s-1YAML\s0.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. 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, \*(C`Bicycle-\*(C'isa('Vehicle')> and also all the things that \*(C`Vehicle\*(C' and \*(C`Class::Spiffy\*(C' export, will go into \*(C`Bicycle\*(C', except \*(C`field\*(C'.

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.

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 \*(C`-base\*(C'.

Spiffy MIXINs & ROLEs

If you've done much \s-1OO\s0 programming in Perl you've probably used Multiple Inheritance (\s-1MI\s0), and if you've done much \s-1MI\s0 you've probably run into weird problems and headaches. Some languages like Ruby, attempt to resolve \s-1MI\s0 issues using a technique called mixins. Basically, all Ruby classes use only Single Inheritance (\s-1SI\s0), 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 \s-1SI\s0 \s-1ISA\s0 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;

\*(C`A-D\*(C' and \*(C`A-C\*(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 \*(C`super\*(C'.

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 \*(C`can\*(C' 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, \*(C`walk\*(C' and \*(C`run\*(C' are methods that E can do, and \*(C`tools\*(C' and \*(C`sharp_tools\*(C' are roles of class E. How does class E define these roles? It very simply defines methods called \*(C`_role_tools\*(C' and \*(C`_role_sharp_tools\*(C' 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 \s-1XXX\s0 function is very handy for debugging because you can insert it almost anywhere, and it will dump your data in nice clean \s-1YAML\s0. 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);

\s-1XXX\s0 is easy to insert and remove. It is also a tradition to mark uncertain areas of code with \s-1XXX\s0. This will make the debugging dumpers easy to spot if you forget to take them out.

\s-1WWW\s0 and \s-1YYY\s0 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 \s-1ZZZ\s0 when you need to die with both a \s-1YAML\s0 dump and a full stack trace.

The debugging functions are exported by default if you use the \*(C`-base\*(C' option, but only if you have previously used the \*(C`-XXX\*(C' option. To export all 4 functions use the export tag:

use SomeSpiffyModule ':XXX';

To force the debugging functions to use Data::Dumper instead of \s-1YAML:\s0

use SomeSpiffyModule -dumper;

Spiffy FUNCTIONS

This section describes the functions the Class::Spiffy exports. The \*(C`field\*(C', \*(C`const\*(C', \*(C`stub\*(C' and \*(C`super\*(C' functions are only exported when you use the \*(C`-base\*(C' option.

  • field Defines accessor methods for a field of your class: 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 passed to \*(C`field\*(C' is the name of the attribute being defined. Accessors can be given an optional default value. This value will be returned if no value for the field has been set in the object.

  • const const bar => 42; The \*(C`const\*(C' function is similar to <field> except that it is immutable. It also does not store data in the object. You probably always want to give a \*(C`const\*(C' a default value, otherwise the generated method will be somewhat useless.

  • stub stub 'cigar'; The \*(C`stub\*(C' function generates a method that will die with an appropriate message. The idea is that subclasses must implement these methods so that the stub methods don't get called.

  • super If this function is called without any arguments, it will call the same method that it is in, higher up in the \s-1ISA\s0 tree, passing it all the same arguments. If it is called with arguments, it will use those arguments with $self in the front. In other words, it just works like you'd expect. 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; } \*(C`super\*(C' will simply do nothing if there is no super method. Finally, \*(C`super\*(C' does the right thing in \s-1AUTOLOAD\s0 subroutines.

Spiffy METHODS

This section lists all of the methods that any subclass of Class::Spiffy automatically inherits.

  • mixin A method to mixin a class at runtime. Takes the same arguments as \*(C`use mixin ...\*(C'. Makes the target class a mixin of the caller. $self->mixin('SomeClass'); $object->mixin('SomeOtherClass' => 'some_method');

  • parse_arguments This method takes a list of arguments and groups them into pairs. It allows for boolean arguments which may or may not have a value (defaulting to 1). The method returns a hash reference of all the pairs as keys and values in the hash. Any arguments that cannot be paired, are returned as a list. Here is an example: 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'.

  • boolean_arguments Returns the list of arguments that are recognized as being boolean. Override this method to define your own list.

  • paired_arguments Returns the list of arguments that are recognized as being paired. Override this method to define your own list.

Spiffy ARGUMENTS

When you \*(C`use\*(C' the Class::Spiffy module or a subclass of it, you can pass it a list of arguments. These arguments are parsed using the \*(C`parse_arguments\*(C' method described above. The special argument \*(C`- base\*(C', is used to make the current package a subclass of the Class::Spiffy module being used.

Any non-paired parameters act like a normal import list; just like those used with the Exporter module.

USING Class::Spiffy WITH base.pm

The proper way to use a Class::Spiffy module as a base class is with the \*(C`-base\*(C' parameter to the \*(C`use\*(C' statement. This differs from typical modules where you would want to \*(C`use base\*(C'.

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

Now it may be hard to keep track of what's Spiffy and what is not. Therefore Class::Spiffy has actually been made to work with base.pm. You can say:

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

\*(C`use base\*(C' is also very useful when your class is not an actual module (a separate file) but just a package in some file that has already been loaded. \*(C`base\*(C' will work whether the class is a module or not, while the \*(C`-base\*(C' syntax cannot work that way, since \*(C`use\*(C' always tries to load a module.

base.pm Caveats

To make Class::Spiffy work with base.pm, a dirty trick was played. Class::Spiffy swaps \*(C`base::import\*(C' 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.

  • Class::Spiffy must be loaded first. If Class::Spiffy is not loaded and \*(C`use base\*(C' 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. If you get this error, simply put a statement like this up front in your code: use Class::Spiffy ();

  • No Mixing \*(C`base.pm\*(C' can take multiple arguments. And this works with Class::Spiffy as long as all the base classes are Spiffy, or they are all non-Spiffy. If they are mixed, Class::Spiffy will die. In this case just use separate \*(C`use base\*(C' statements.

AUTHOR

Ingy dA\*~Xt Net <[email protected]>

COPYRIGHT

Copyright (c) 2006. Ingy dA\*~Xt 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>