2 Spiffy - Spiffy Perl Interface Framework For You
11 if ($self->mood eq ':-(') {
19 "Spiffy" is a framework and methodology for doing object oriented (OO)
20 programming in Perl. Spiffy combines the best parts of Exporter.pm,
21 base.pm, mixin.pm and SUPER.pm into one magic foundation class. It
22 attempts to fix all the nits and warts of traditional Perl OO, in a
23 clean, straightforward and (perhaps someday) standard way.
25 Spiffy borrows ideas from other OO languages like Python, Ruby, Java and
26 Perl 6. It also adds a few tricks of its own.
28 If you take a look on CPAN, there are a ton of OO related modules. When
29 starting a new project, you need to pick the set of modules that makes
30 most sense, and then you need to use those modules in each of your
31 classes. Spiffy, on the other hand, has everything you'll probably need
32 in one module, and you only need to use it once in one of your classes.
33 If you make Spiffy.pm the base class of the basest class in your
34 project, Spiffy will automatically pass all of its magic to all of your
35 subclasses. You may eventually forget that you're even using it!
37 The most striking difference between Spiffy and other Perl object
38 oriented base classes, is that it has the ability to export things. If
39 you create a subclass of Spiffy, all the things that Spiffy exports will
40 automatically be exported by your subclass, in addition to any more
41 things that you want to export. And if someone creates a subclass of
42 your subclass, all of those things will be exported automatically, and
43 so on. Think of it as "Inherited Exportation", and it uses the familiar
44 Exporter.pm specification syntax.
46 To use Spiffy or any subclass of Spiffy as a base class of your class,
47 you specify the "-base" argument to the "use" command.
49 use MySpiffyBaseModule -base;
51 You can also use the traditional "use base 'MySpiffyBaseModule';" syntax
52 and everything will work exactly the same. The only caveat is that
53 Spiffy.pm must already be loaded. That's because Spiffy rewires base.pm
54 on the fly to do all the Spiffy magics.
56 Spiffy has support for Ruby-like mixins with Perl6-like roles. Just like
57 "base" you can use either of the following invocations:
59 use mixin 'MySpiffyBaseModule';
60 use MySpiffyBaseModule -mixin;
62 The second version will only work if the class being mixed in is a
63 subclass of Spiffy. The first version will work in all cases, as long as
64 Spiffy has already been loaded.
66 To limit the methods that get mixed in, use roles. (Hint: they work just
67 like an Exporter list):
69 use MySpiffyBaseModule -mixin => qw(:basics x y !foo);
71 In object oriented Perl almost every subroutine is a method. Each method
72 gets the object passed to it as its first argument. That means
73 practically every subroutine starts with the line:
77 Spiffy provides a simple, optional filter mechanism to insert that line
78 for you, resulting in cleaner code. If you figure an average method has
79 10 lines of code, that's 10% of your code! To turn this option on, you
80 just use the "-Base" option instead of the "-base" option, or add the
81 "-selfless" option. If source filtering makes you queazy, don't use the
82 feature. I personally find it addictive in my quest for writing squeaky
83 clean, maintainable code.
85 A useful feature of Spiffy is that it exports two functions: "field" and
86 "const" that can be used to declare the attributes of your class, and
87 automatically generate accessor methods for them. The only difference
88 between the two functions is that "const" attributes can not be
89 modified; thus the accessor is much faster.
91 One interesting aspect of OO programming is when a method calls the same
92 method from a parent class. This is generally known as calling a super
93 method. Perl's facility for doing this is butt ugly:
98 $self->SUPER::cleanup(@_);
101 Spiffy makes it, er, super easy to call super methods. You just use the
102 "super" function. You don't need to pass it any arguments because it
103 automatically passes them on for you. Here's the same function with
111 Spiffy has a special method for parsing arguments called
112 "parse_arguments", that it also uses for parsing its own arguments. You
113 declare which arguments are boolean (singletons) and which ones are
114 paired, with two special methods called "boolean_arguments" and
115 "paired_arguments". Parse arguments pulls out the booleans and pairs and
116 returns them in an anonymous hash, followed by a list of the unmatched
119 Finally, Spiffy can export a few debugging functions "WWW", "XXX", "YYY"
120 and "ZZZ". Each of them produces a YAML dump of its arguments. WWW warns
121 the output, XXX dies with the output, YYY prints the output, and ZZZ
122 confesses the output. If YAML doesn't suit your needs, you can switch
123 all the dumps to Data::Dumper format with the "-dumper" option.
128 Spiffy implements a completely new idea in Perl. Modules that act both
129 as object oriented classes and that also export functions. But it takes
130 the concept of Exporter.pm one step further; it walks the entire @ISA
131 path of a class and honors the export specifications of each module.
132 Since Spiffy calls on the Exporter module to do this, you can use all
133 the fancy interface features that Exporter has, including tags and
136 Spiffy considers all the arguments that don't begin with a dash to
137 comprise the export specification.
141 our $SERIAL_NUMBER = 0;
142 our @EXPORT = qw($SERIAL_NUMBER);
143 our @EXPORT_BASE = qw(tire horn);
146 use Vehicle -base, '!field';
147 $self->inflate(tire);
149 In this case, "Bicycle-"isa('Vehicle')> and also all the things that
150 "Vehicle" and "Spiffy" export, will go into "Bicycle", except "field".
152 Exporting can be very helpful when you've designed a system with
153 hundreds of classes, and you want them all to have access to some
154 functions or constants or variables. Just export them in your main base
155 class and every subclass will get the functions they need.
157 You can do almost everything that Exporter does because Spiffy delegates
158 the job to Exporter (after adding some Spiffy magic). Spiffy offers a
159 @EXPORT_BASE variable which is like @EXPORT, but only for usages that
162 Spiffy MIXINs & ROLEs
163 If you've done much OO programming in Perl you've probably used Multiple
164 Inheritance (MI), and if you've done much MI you've probably run into
165 weird problems and headaches. Some languages like Ruby, attempt to
166 resolve MI issues using a technique called mixins. Basically, all Ruby
167 classes use only Single Inheritance (SI), and then *mixin* functionality
168 from other modules if they need to.
170 Mixins can be thought of at a simplistic level as *importing* the
171 methods of another class into your subclass. But from an implementation
172 standpoint that's not the best way to do it. Spiffy does what Ruby does.
173 It creates an empty anonymous class, imports everything into that class,
174 and then chains the new class into your SI ISA path. In other words, if
182 You end up with a single inheritance chain of classes like this:
184 A << A-D << A-C << B;
186 "A-D" and "A-C" are the actual package names of the generated classes.
187 The nice thing about this style is that mixing in C doesn't clobber any
188 methods in A, and D doesn't conflict with A or C either. If you mixed in
189 a method in C that was also in A, you can still get to it by using
192 When Spiffy mixes in C, it pulls in all the methods in C that do not
193 begin with an underscore. Actually it goes farther than that. If C is a
194 subclass it will pull in every method that C "can" do through
195 inheritance. This is very powerful, maybe too powerful.
197 To limit what you mixin, Spiffy borrows the concept of Roles from Perl6.
198 The term role is used more loosely in Spiffy though. It's much like an
199 import list that the Exporter module uses, and you can use groups (tags)
200 and negation. If the first element of your list uses negation, Spiffy
201 will start with all the methods that your mixin class can do.
203 use E -mixin => qw(:tools walk !run !:sharp_tools);
205 In this example, "walk" and "run" are methods that E can do, and "tools"
206 and "sharp_tools" are roles of class E. How does class E define these
207 roles? It very simply defines methods called "_role_tools" and
208 "_role_sharp_tools" which return lists of more methods. (And possibly
209 other roles!) The neat thing here is that since roles are just methods,
210 they too can be inherited. Take that Perl6!
213 By using the "-Base" flag instead of "-base" you never need to write the
218 This statement is added to every subroutine in your class by using a
219 source filter. The magic is simple and fast, so there is litte
220 performance penalty for creating clean code on par with Ruby and Python.
233 is exactly the same as:
237 use strict;use warnings;
238 sub crazy {my $self = shift;
241 sub wacky {my $self = shift; }
247 Note that the empty parens after the subroutine "new" keep it from
248 having a $self added. Also note that the extra code is added to existing
249 lines to ensure that line numbers are not altered.
251 "-Base" also turns on the strict and warnings pragmas, and adds that
252 annoying '1;' line to your module.
255 Spiffy now has support for private methods when you use the '-Base'
256 filter mechanism. You just declare the subs with the "my" keyword, and
257 call them with a '$' in front. Like this:
260 use SomethingSpiffy -Base;
262 # normal public method
267 # private lexical method. uncallable from outside this file.
273 The XXX function is very handy for debugging because you can insert it
274 almost anywhere, and it will dump your data in nice clean YAML. Take the
277 my @stuff = grep { /keen/ } $self->find($a, $b);
279 If you have a problem with this statement, you can debug it in any of
282 XXX my @stuff = grep { /keen/ } $self->find($a, $b);
283 my @stuff = XXX grep { /keen/ } $self->find($a, $b);
284 my @stuff = grep { /keen/ } XXX $self->find($a, $b);
285 my @stuff = grep { /keen/ } $self->find(XXX $a, $b);
287 XXX is easy to insert and remove. It is also a tradition to mark
288 uncertain areas of code with XXX. This will make the debugging dumpers
289 easy to spot if you forget to take them out.
291 WWW and YYY are nice because they dump their arguments and then return
292 the arguments. This way you can insert them into many places and still
293 have the code run as before. Use ZZZ when you need to die with both a
294 YAML dump and a full stack trace.
296 The debugging functions are exported by default if you use the "-base"
297 option, but only if you have previously used the "-XXX" option. To
298 export all 4 functions use the export tag:
300 use SomeSpiffyModule ':XXX';
302 To force the debugging functions to use Data::Dumper instead of YAML:
304 use SomeSpiffyModule -dumper;
307 This section describes the functions the Spiffy exports. The "field",
308 "const", "stub" and "super" functions are only exported when you use the
309 "-base" or "-Base" options.
312 Defines accessor methods for a field of your class:
322 push @{$self->{bar}}, $self->foo;
325 The first parameter passed to "field" is the name of the attribute
326 being defined. Accessors can be given an optional default value.
327 This value will be returned if no value for the field has been set
333 The "const" function is similar to <field> except that it is
334 immutable. It also does not store data in the object. You probably
335 always want to give a "const" a default value, otherwise the
336 generated method will be somewhat useless.
341 The "stub" function generates a method that will die with an
342 appropriate message. The idea is that subclasses must implement
343 these methods so that the stub methods don't get called.
346 If this function is called without any arguments, it will call the
347 same method that it is in, higher up in the ISA tree, passing it all
348 the same arguments. If it is called with arguments, it will use
349 those arguments with $self in the front. In other words, it just
350 works like you'd expect.
353 super; # Same as $self->SUPER::foo(@_);
354 super('hello'); # Same as $self->SUPER::foo('hello');
364 "super" will simply do nothing if there is no super method. Finally,
365 "super" does the right thing in AUTOLOAD subroutines.
368 This section lists all of the methods that any subclass of Spiffy
369 automatically inherits.
372 A method to mixin a class at runtime. Takes the same arguments as
373 "use mixin ...". Makes the target class a mixin of the caller.
375 $self->mixin('SomeClass');
376 $object->mixin('SomeOtherClass' => 'some_method');
379 This method takes a list of arguments and groups them into pairs. It
380 allows for boolean arguments which may or may not have a value
381 (defaulting to 1). The method returns a hash reference of all the
382 pairs as keys and values in the hash. Any arguments that cannot be
383 paired, are returned as a list. Here is an example:
385 sub boolean_arguments { qw(-has_spots -is_yummy) }
386 sub paired_arguments { qw(-name -size) }
387 my ($pairs, @others) = $self->parse_arguments(
396 After this call, $pairs will contain:
405 and @others will contain 'red', 'white', and 'black'.
408 Returns the list of arguments that are recognized as being boolean.
409 Override this method to define your own list.
412 Returns the list of arguments that are recognized as being paired.
413 Override this method to define your own list.
416 When you "use" the Spiffy module or a subclass of it, you can pass it a
417 list of arguments. These arguments are parsed using the
418 "parse_arguments" method described above. The special argument "-base",
419 is used to make the current package a subclass of the Spiffy module
422 Any non-paired parameters act like a normal import list; just like those
423 used with the Exporter module.
425 USING Spiffy WITH base.pm
426 The proper way to use a Spiffy module as a base class is with the
427 "-base" parameter to the "use" statement. This differs from typical
428 modules where you would want to "use base".
431 use Spiffy::Module -base;
432 use base 'NonSpiffy::Module';
434 Now it may be hard to keep track of what's Spiffy and what is not.
435 Therefore Spiffy has actually been made to work with base.pm. You can
439 use base 'Spiffy::Module';
440 use base 'NonSpiffy::Module';
442 "use base" is also very useful when your class is not an actual module
443 (a separate file) but just a package in some file that has already been
444 loaded. "base" will work whether the class is a module or not, while the
445 "-base" syntax cannot work that way, since "use" always tries to load a
449 To make Spiffy work with base.pm, a dirty trick was played. Spiffy swaps
450 "base::import" with its own version. If the base modules are not Spiffy,
451 Spiffy calls the original base::import. If the base modules are Spiffy,
452 then Spiffy does its own thing.
454 There are two caveats.
456 * Spiffy must be loaded first.
457 If Spiffy is not loaded and "use base" is invoked on a Spiffy
458 module, Spiffy will die with a useful message telling the author to
459 read this documentation. That's because Spiffy needed to do the
460 import swap beforehand.
462 If you get this error, simply put a statement like this up front in
468 "base.pm" can take multiple arguments. And this works with Spiffy as
469 long as all the base classes are Spiffy, or they are all non-Spiffy.
470 If they are mixed, Spiffy will die. In this case just use separate
471 "use base" statements.
474 Spiffy is a wonderful way to do OO programming in Perl, but it is still
475 a work in progress. New things will be added, and things that don't work
476 well, might be removed.
479 Ingy döt Net <ingy@cpan.org>
482 Copyright (c) 2006. Ingy döt Net. All rights reserved. Copyright (c)
483 2004. Brian Ingerson. All rights reserved.
485 This program is free software; you can redistribute it and/or modify it
486 under the same terms as Perl itself.
488 See <http://www.perl.com/perl/misc/Artistic.html>