1Class::Prototyped(3)  User Contributed Perl Documentation Class::Prototyped(3)
2
3
4

NAME

6       "Class::Prototyped" - Fast prototype-based OO programming in Perl
7

SYNOPSIS

9           use strict;
10           use Class::Prototyped ':EZACCESS';
11
12           $, = ' '; $\ = "\n";
13
14           my $p = Class::Prototyped->new(
15             field1 => 123,
16             sub1   => sub { print "this is sub1 in p" },
17             sub2   => sub { print "this is sub2 in p" }
18           );
19
20           $p->sub1;
21           print $p->field1;
22           $p->field1('something new');
23           print $p->field1;
24
25           my $p2 = Class::Prototyped::new(
26             'parent*' => $p,
27             field2    => 234,
28             sub2      => sub { print "this is sub2 in p2" }
29           );
30
31           $p2->sub1;
32           $p2->sub2;
33           print ref($p2), $p2->field1, $p2->field2;
34           $p2->field1('and now for something different');
35           print ref($p2), $p2->field1;
36
37           $p2->addSlots( sub1 => sub { print "this is sub1 in p2" } );
38           $p2->sub1;
39
40           print ref($p2), "has slots", $p2->reflect->slotNames;
41
42           $p2->reflect->include( 'xx.pl' ); # includes xx.pl in $p2's package
43           print ref($p2), "has slots", $p2->reflect->slotNames;
44           $p2->aa();    # calls aa from included file xx.pl
45
46           $p2->deleteSlots('sub1');
47           $p2->sub1;
48

DESCRIPTION

50       This package provides for efficient and simple prototype-based program‐
51       ming in Perl. You can provide different subroutines for each object,
52       and also have objects inherit their behavior and state from another
53       object.
54
55       The structure of an object is inspected and modified through mirrors,
56       which are created by calling "reflect" on an object or class that
57       inherits from "Class::Prototyped".
58
59       Installation instructions
60
61       This module requires "Module::Build 0.24" to use the automated instal‐
62       lation procedures.  With "Module::Build" installed:
63
64         Build.PL
65         perl build test
66         perl build install
67
68       It can be installed under ActivePerl for Win32 by downloading the PPM
69       from CPAN (the file has the extension ".ppm.zip").  To install, down‐
70       load the ".ppm.zip" file, uncompress it, and execute:
71
72         ppm install Class-Prototyped.ppd
73
74       The module can also be installed manually by copying "lib/Class/Proto‐
75       typed.pm" to "perl/site/lib/Class/Prototyped.pm" (along with "Graph.pm"
76       if you want it).
77

WHEN TO USE THIS MODULE

79       When I reach for "Class::Prototyped", it's generally because I really
80       need it.  When the cleanest way of solving a problem is for the code
81       that uses a module to subclass from it, that is generally a sign that
82       "Class::Prototyped" would be of use.  If you find yourself avoiding the
83       problem by passing anonymous subroutines as parameters to the "new"
84       method, that's another good sign that you should be using prototype
85       based programming.  If you find yourself storing anonymous subroutines
86       in databases, configuration files, or text files, and then writing in‐
87       frastructure to handle calling those anonymous subroutines, that's yet
88       another sign.  When you expect the people using your module to want to
89       change the behavior, override subroutines, and so forth, that's a sign.
90

CONCEPTS

92       Slots
93
94       "Class::Prototyped" borrows very strongly from the language Self (see
95       http://www.sun.com/research/self for more information).  The core con‐
96       cept in Self is the concept of a slot.  Think of slots as being entries
97       in a hash, except that instead of just pointing to data, they can point
98       to objects, code, or parent objects.
99
100       So what happens when you send a message to an object (that is to say,
101       you make a method call on the object)?  First, Perl looks for that slot
102       in the object.  If it can't find that slot in the object, it searches
103       for that slot in one of the object's parents (which we'll come back to
104       later).  Once it finds the slot, if the slot is a block of code, it
105       evaluates the code and returns the return value.  If the slot refer‐
106       ences data, it returns that data.  If you assign to a data slot
107       (through a method call), it modifies the data.
108
109       Distinguishing data slots and method slots is easy - the latter are
110       references to code blocks, the former are not.  Distinguishing parent
111       slots is not so easy, so instead a simple naming convention is used.
112       If the name of the slot ends in an asterisk, the slot is a parent slot.
113       If you have programmed in Self, this naming convention will feel very
114       familiar.
115
116       Reflecting
117
118       In Self, to examine the structure of an object, you use a mirror.  Just
119       like using his shield as a mirror enabled Perseus to slay Medusa, hold‐
120       ing up a mirror enables us to look upon an object's structure without
121       name space collisions.
122
123       Once you have a mirror, you can add and delete slots like so:
124
125           my $cp = Class::Prototyped->new();
126           my $mirror = $cp->reflect();
127           $mirror->addSlots(
128             field1 => 'foo',
129             sub1   => sub {
130               print "this is sub1 printing field1: '".$_[0]->field1."'\n";
131             },
132           );
133
134           $mirror->deleteSlot('sub1');
135
136       In addition, there is a more verbose syntax for "addSlots" where the
137       slot name is replaced by an anonymous array - this is most commonly
138       used to control the slot attributes.
139
140           $cp->reflect->addSlot(
141             [qw(field1 FIELD)] => 'foo',
142             [qw(sub1 METHOD)]  => sub { print "hi there.\n"; },
143           );
144
145       Because the mirror methods "super", "addSlot"("s"), "deleteSlot"("s"),
146       and "getSlot"("s") are called frequently on objects, there is an import
147       keyword ":EZACCESS" that adds methods to the object space that call the
148       appropriate reflected variants.
149
150       Slot Attributes
151
152       Slot attributes allow the user to specify additional information and
153       behavior relating to a specific slot in an extensible manner.  For
154       instance, one might want to mark a specific field slot as constant or
155       to attach a description to a given slot.
156
157       Slot attributes are divided up in two ways.  The first is by the type
158       of slot - "FIELD", "METHOD", or "PARENT".  Some slot attributes apply
159       to all three, some to just two, and some to only one.  The second divi‐
160       sion is on the type of slot attribute:
161
162       implementor
163           These are responsible for implementing the behavior of a slot.  An
164           example is a "FIELD" slot with the attribute "constant".  A slot is
165           only allowed one implementor.  All slot types have a default imple‐
166           mentor.  For "FIELD" slots, it is a read-write scalar.  For
167           "METHOD" slots, it is the passed anonymous subroutine.  For "PAR‐
168           ENT" slots, "implementor" and "filter" slot attributes don't really
169           make sense.
170
171       filter
172           These filter access to the "implementor".  The quintessential exam‐
173           ple is the "profile" attribute.  When set, this increments a
174           counter in $Class::Prototyped::Mirror::PROFILE::counts every time
175           the underlying "FIELD" or "METHOD" is accessed.  Filter attributes
176           can be stacked, so each attribute is assigned a rank with lower
177           values being closer to the "implementor" and higher values being
178           closer to the caller.
179
180       advisory
181           These slot attributes serve one of two purposes.  They can be used
182           to store information about the slot (i.e. "description"
183           attributes), and they can be used to pass information to the
184           "addSlots" method (i.e. the "promote" attribute, which can be used
185           to promote a new "PARENT" slot ahead of all the existing "PARENT"
186           slots).
187
188       There is currently no formal interface for creating your own attributes
189       - if you feel the need for new attributes, please contact the main‐
190       tainer first to see if it might make sense to add the new attribute to
191       "Class::Prototyped".  If not, the contact might provide enough impetus
192       to define a formal interface.  The attributes are currently defined in
193       $Class::Prototyped::Mirror::attributes.
194
195       Finally, see the "defaultAttributes" method for information about set‐
196       ting default attributes.  This can be used, for instance, to turn on
197       profiling everywhere.
198
199       Classes vs. Objects
200
201       In Self, everything is an object and there are no classes at all.
202       Perl, for better or worse, has a class system based on packages.  We
203       decided that it would be better not to throw out the conventional way
204       of structuring inheritance hierarchies, so in "Class::Prototyped",
205       classes are first-class objects.
206
207       However, objects are not first-class classes.  To understand this
208       dichotomy, we need to understand that there is a difference between the
209       way "classes" and the way "objects" are expected to behave.  The cen‐
210       tral difference is that "classes" are expected to persist whether or
211       not that are any references to them.  If you create a class, the class
212       exists whether or not it appears in anyone's @ISA and whether or not
213       there are any objects in it.  Once a class is created, it persists
214       until the program terminates.
215
216       Objects, on the other hand, should follow the normal behaviors of ref‐
217       erence-counted destruction - once the number of references to them
218       drops to zero, they should miraculously disappear - the memory they
219       used needs to be returned to Perl, their "DESTROY" methods need to be
220       called, and so forth.
221
222       Since we don't require this behavior of classes, it's easy to have a
223       way to get from a package name to an object - we simply stash the
224       object that implements the class in $Class::Prototyped::Mir‐
225       ror::objects{$package}.  But we can't do this for objects, because if
226       we do the object will persist forever because that reference will
227       always exist.
228
229       Weak references would solve this problem, but weak references are still
230       considered alpha and unsupported ("$WeakRef::VERSION = 0.01"), and we
231       didn't want to make "Class::Prototyped" dependent on such a module.
232
233       So instead, we differentiate between classes and objects.  In a nut‐
234       shell, if an object has an explicit package name (i.e. something other
235       than the auto-generated one), it is considered to be a class, which
236       means it persists even if the object goes out of scope.
237
238       To create such an object, use the "newPackage" method, like so (the
239       encapsulating block exists solely to demonstrate that classes are not
240       scoped):
241
242           {
243             my $object = Class::Prototyped->newPackage('MyClass',
244                 field => 1,
245                 double => sub {$_[0]->field*2}
246               );
247           }
248
249           print MyClass->double,"\n";
250
251       Notice that the class persists even though $object goes out of scope.
252       If $object were created with an auto-generated package, that would not
253       be true.  Thus, for instance, it would be a very, very, very bad idea
254       to add the package name of an object as a parent to another object -
255       when the first object goes out of scope, the package will disappear,
256       but the second object will still have it in it's @ISA.
257
258       Except for the crucial difference that you should never, ever, ever
259       make use of the package name for an object for any purpose other than
260       printing it to the screen, objects and classes are simply different
261       ways of inspecting the same entity.
262
263       To go from an object to a package, you can do one of the following:
264
265           $package = ref($object);
266           $package = $object->reflect->package;
267
268       The two are equivalent, although the first is much faster.  Just remem‐
269       ber, if $object is in an auto-generated package, don't do anything with
270       that $package but print it.
271
272       To go from a package to an object, you do this:
273
274           $object = $package->reflect->object;
275
276       Note that $package is simple the name of the package - the following
277       code works perfectly:
278
279           $object = MyClass->reflect->object;
280
281       But keep in mind that $package has to be a class, not an auto-generated
282       package name for an object.
283
284       Class Manipulation
285
286       This lets us have tons of fun manipulating classes at run time. For
287       instance, if you wanted to add, at run-time, a new method to the
288       "MyClass" class?  Assuming that the "MyClass" inherits from
289       "Class::Prototyped" or that you have specified ":REFLECT" on the "use
290       Class::Prototyped" call, you simply write:
291
292           MyClass->reflect->addSlot(myMethod => sub {print "Hi there\n"});
293
294       If you want to access a class that doesn't inherit from "Class::Proto‐
295       typed", and you want to avoid specifying ":REFLECT" (which adds
296       "reflect" to the "UNIVERSAL" package), you can make the call like so:
297
298           my $mirror = Class::Prototyped::Mirror->new('MyClass');
299           $mirror->addSlot(myMethod => sub {print "Hi there\n"});
300
301       Just as you can "clone" objects, you can "clone" classes that are
302       derived from "Class::Prototyped". This creates a new object that has a
303       copy of all of the slots that were defined in the class.  Note that if
304       you simply want to be able to use "Data::Dumper" on a class, calling
305       "MyClass->reflect->object" is the preferred approach.  Even easier
306       would be to use the "dump" mirror method.
307
308       The code that implements reflection on classes automatically creates
309       slot names for package methods as well as parent slots for the entries
310       in @ISA.  This means that you can code classes like you normally do -
311       by doing the inheritance in @ISA and writing package methods.
312
313       If you manually add subroutines to a package at run-time and want the
314       slot information updated properly (although this really should be done
315       via the "addSlots" mechanism, but maybe you're twisted:), you should do
316       something like:
317
318           $package->reflect->_vivified_methods(0);
319           $package->reflect->_autovivify_methods;
320
321       Parent Slots
322
323       Adding parent slots is no different than adding normal slots - the nam‐
324       ing scheme takes care of differentiating.
325
326       Thus, to add $foo as a parent to $bar, you write:
327
328           $bar->reflect->addSlot('fooParent*' => $foo);
329
330       However, keeping with our concept of classes as first class objects,
331       you can also write the following:
332
333           $bar->reflect->addSlot('mixIn*' => 'MyMix::Class');
334
335       It will automatically require the module in the namespace of $bar and
336       make the module a parent of the object.  This can load a module from
337       disk if needed.
338
339       If you're lazy, you can add parents without names like so:
340
341           $bar->reflect->addSlot('*' => $foo);
342
343       The slots will be automatically named for the package passed in - in
344       the case of "Class::Prototyped" objects, the package is of the form
345       "PKG0x12345678".  In the following example, the parent slot will be
346       named "MyMix::Class*".
347
348           $bar->reflect->addSlot('*' => 'MyMix::Class');
349
350       Parent slots are added to the inheritance hierarchy in the order that
351       they were added.  Thus, in the following code, slots that don't exist
352       in $foo are looked up in $fred (and all of its parent slots) before
353       being looked up in $jill.
354
355           $foo->reflect->addSlots('fred*' => $fred, 'jill*' => $jill);
356
357       Note that "addSlot" and "addSlots" are identical - the variants exist
358       only because it looks ugly to add a single slot by calling "addSlots".
359
360       If you need to reorder the parent slots on an object, look at "pro‐
361       moteParents".  That said, there's a shortcut for prepending a slot to
362       the inheritance hierarchy.  Simply define 'promote' as a slot attribute
363       using the extended slot syntax.
364
365       Finally, in keeping with our principle that classes are first-class
366       object, the inheritance hierarchy of classes can be modified through
367       "addSlots" and "deleteSlots", just like it can for objects.  The fol‐
368       lowing code adds the $foo object as a parent of the "MyClass" class,
369       prepending it to the inheritance hierarchy:
370
371           MyClass->reflect->addSlots([qw(foo* promote)] => $foo);
372
373       Operator Overloading
374
375       In "Class::Prototyped", you do operator overloading by adding slots
376       with the right name.  First, when you do the "use" on "Class::Proto‐
377       typed", make sure to pass in ":OVERLOAD" so that the operator overload‐
378       ing support is enabled.
379
380       Then simply pass the desired methods in as part of the object creation
381       like so:
382
383           $foo = Class::Prototyped->new(
384               value => 3,
385               '""'  => sub { my $self = shift; $self->value( $self->value + 1 ) },
386           );
387
388       This creates an object that increments its field "value" by one and
389       returns that incremented value whenever it is stringified.
390
391       Since there is no way to find out which operators are overloaded, if
392       you add overloading to a class through the use of "use overload", that
393       behavior will not show up as slots when reflecting on the class. How‐
394       ever, "addSlots" does work for adding operator overloading to classes.
395       Thus, the following code does what is expected:
396
397           Class::Prototyped->newPackage('MyClass');
398           MyClass->reflect->addSlots(
399               '""' => sub { my $self = shift; $self->value( $self->value + 1 ) },
400           );
401
402           $foo = MyClass->new( value => 2 );
403           print $foo, "\n";
404
405       Object Class
406
407       The special parent slot "class*" is used to indicate object class.
408       When you create "Class::Prototyped" objects by calling "Class::Proto‐
409       typed->new()", the "class*" slot is not set.  If, however, you create
410       objects by calling "new" on a class or object that inherits from
411       "Class::Prototyped", the slot "class*" points to the package name if
412       "new" was called on a named class, or the object if "new" was called on
413       an object.
414
415       The value of this slot can be returned quite easily like so:
416
417           $foo->reflect->class;
418
419       Calling Inherited Methods
420
421       Methods (and fields) inherited from prototypes or classes are not gen‐
422       erally available using the usual Perl "$self->SUPER::something()" mech‐
423       anism.
424
425       The reason for this is that "SUPER::something" is hardcoded to the
426       package in which the subroutine (anonymous or otherwise) was defined.
427       For the vast majority of programs, this will be "main::", and thus
428       "SUPER::" will look in @main::ISA (not a very useful place to look).
429
430       To get around this, a very clever wrapper can be automatically placed
431       around your subroutine that will automatically stash away the package
432       to which the subroutine is attached.  From within the subroutine, you
433       can use the "super" mirror method to make an inherited call.  However,
434       because we'd rather not write code that attempts to guess as to whether
435       or not the subroutine uses the "super" construct, you have to tell
436       "addSlots" that the subroutine needs to have this wrapper placed around
437       it.  To do this, simply use the extended "addSlots" syntax (see the
438       method description for more information) and pass in the slot attribute
439       'superable'.  The following examples use the minimalist form of the
440       extended syntax.
441
442       For instance, the following code will work:
443
444           use Class::Prototyped;
445
446           my $p1 = Class::Prototyped->new(
447               method => sub { print "this is method in p1\n" },
448           );
449
450           my $p2 = Class::Prototyped->new(
451               '*'                     => $p1,
452               [qw(method superable)]' => sub {
453                   print "this is method in p2 calling method in p1: ";
454                   $_[0]->reflect->super('method');
455               },
456           );
457
458       To make things easier, if you specify ":EZACCESS" during the import,
459       "super" can be called directly on an object rather than through its
460       mirror.
461
462       The other thing of which you need to be aware is copying methods from
463       one object to another.  The proper way to do this is like so:
464
465           $foo->reflect->addSlot($bar->reflect->getSlot('method'));
466
467       When the "getSlot" method is called in an array context, it returns
468       both the complete format for the slot identifier and the slot.  This
469       ensures that slot attributes are passed along, including the "supera‐
470       ble" attribute.
471
472       Finally, to help protect the code, the "super" method is smart enough
473       to determine whether it was called within a wrapped subroutine.  If it
474       wasn't, it croaks indicating that the method should have had the
475       "superable" attribute set when it was added.  If you wish to disable
476       this checking (which will improve the performance of your code, of
477       course, but could result in very hard to trace bugs if you haven't been
478       careful), see the import option ":SUPER_FAST".
479

PERFORMANCE NOTES

481       It is important to be aware of where the boundaries of prototyped based
482       programming lie, especially in a language like Perl that is not opti‐
483       mized for it.  For instance, it might make sense to implement every
484       field in a database as an object.  Those field objects would in turn be
485       attached to a record class. All of those might be implemented using
486       "Class::Prototyped".  However, it would be very inefficient if every
487       record that got read from the database was stored in a "Class::Proto‐
488       typed" based object (unless, of course, you are storing code in the
489       database).  In that situation, it is generally good to choke off the
490       prototype-based behavior for the individual record objects.  For best
491       performance, it is important to confine "Class::Prototyped" to those
492       portions of the code where behavior is mutable from outside of the mod‐
493       ule.  See the documentation for the "new" method of "Class::Prototyped"
494       for more information about choking off "Class::Prototyped" behavior.
495
496       There are a number of performance hits when using "Class::Prototyped",
497       relative to using more traditional OO code.  It is important to note
498       that these generally lie in the instantiation and creation of classes
499       and objects and not in the actual use of them.  The scripts in the
500       "perf" directory were designed for benchmarking some of this material.
501
502       Class Instantiation
503
504       The normal way of creating a class is like this:
505
506           package Pack_123;
507           sub a {"hi";}
508           sub b {"hi";}
509           sub c {"hi";}
510           sub d {"hi";}
511           sub e {"hi";}
512
513       The most efficient way of doing that using "proper" "Class::Prototyped"
514       methodology looks like this:
515
516           Class::Prototyped->newPackage("Pack_123");
517           push(@P_123::slots, a => sub {"hi";});
518           push(@P_123::slots, b => sub {"hi";});
519           push(@P_123::slots, c => sub {"hi";});
520           push(@P_123::slots, d => sub {"hi";});
521           push(@P_123::slots, e => sub {"hi";});
522           Pack_123->reflect->addSlots(@P_123::slots);
523
524       This approach ensures that the new package gets the proper default
525       attributes and that the slots are created through "addSlots", thus
526       ensuring that default attributes are properly implemented.  It avoids
527       multiple calls to " ->reflect->addSlot", though, which improves perfor‐
528       mance.  The idea behind pushing the slots onto an array is that it
529       enables one to intersperse code with POD, since POD is not permitted
530       inside of a single Perl statement.
531
532       On a Pent 4 1.8GHz machine, the normal code runs in 120 usec, whereas
533       the "Class::Prototyped" code runs in around 640 usec, or over 5 times
534       slower.  A straight call to "addSlots" with all five methods runs in
535       around 510 usec.  Code that creates the package and the mirror without
536       adding slots runs in around 135 usec, so we're looking at an overhead
537       of less than 100 usec per slot.  In a situation where the "compile"
538       time dominates the "execution" time (I'm using those terms loosely as
539       much of what happens in "Class::Prototyped" is technically execution
540       time, but it is activity that traditionally would happen at compile
541       time), "Class::Prototyped" might prove to be too much overhead.  On the
542       otherhand, you may find that demand loading can cut much of that over‐
543       head and can be implemented less painfully than might otherwise be
544       thought.
545
546       Object Instantiation
547
548       There is no need to even compare here.  Blessing a hash into a class
549       takes less than 2 usec.  Creating a new "Class::Prototyped" object
550       takes at least 60 or 70 times longer.  The trick is to avoid creating
551       unnecessary "Class::Prototyped" objects.  If you know that all 10,000
552       database records are going to inherit all of their behavior from the
553       parent class, there is no point in creating 10,000 packages and all the
554       attendant overhead.  The "new" method for "Class::Prototyped" demon‐
555       strates how to ensure that those state objects are created as normal
556       Perl objects.
557
558       Method Calls
559
560       The good news is that method calls are just as fast as normal Perl
561       method calls, inherited or not.  This is because the existing Perl OO
562       machinery has been hijacked in "Class::Prototyped".  The exception to
563       this is if "filter" slot attributes have been used, including "wantar‐
564       ray", "superable", and "profile".  In that situation, the added over‐
565       head is that for a normal Perl subroutine call (which is faster than a
566       method call because it is a static binding)
567
568       Instance Variable Access
569
570       The hash interface is not particularly fast, and neither is it good
571       programming practice.  Using the method interface to access fields is
572       just as fast, however, as using normal getter/setter methods.
573

IMPORT OPTIONS

575       ":OVERLOAD"
576           This configures the support in "Class::Prototyped" for using opera‐
577           tor overloading.
578
579       ":REFLECT"
580           This defines "UNIVERSAL::reflect" to return a mirror for any class.
581           With a mirror, you can manipulate the class, adding or deleting
582           methods, changing its inheritance hierarchy, etc.
583
584       ":EZACCESS"
585           This adds the methods "addSlot", "addSlots", "deleteSlot",
586           "deleteSlots", "getSlot", "getSlots", and "super" to "Class::Proto‐
587           typed".
588
589           This lets you write:
590
591             $foo->addSlot(myMethod => sub {print "Hi there\n"});
592
593           instead of having to write:
594
595             $foo->reflect->addSlot(myMethod => sub {print "Hi there\n"});
596
597           The other methods in "Class::Prototyped::Mirror" should be accessed
598           through a mirror (otherwise you'll end up with way too much name
599           space pollution for your objects:).
600
601           Note that it is bad form for published modules to use ":EZACCESS"
602           as you are polluting everyone else's namespace as well.  If you
603           really want ":EZACCESS" for code you plan to publish, contact the
604           maintainer and we'll see what we can about creating a variant of
605           ":EZACCESS" that adds the shortcut methods to a single class.  Note
606           that using ":EZACCESS" to do "$obj->addSlot()" is actually slower
607           than doing "$obj->reflect->addSlot()".
608
609       ":SUPER_FAST"
610           Switches over to the fast version of "super" that doesn't check to
611           see whether slots that use inherited calls were defined as supera‐
612           ble.
613
614       ":NEW_MAIN"
615           Creates a "new" function in "main::" that creates new "Class::Pro‐
616           totyped" objects.  Thus, you can write code like:
617
618             use Class::Prototyped qw(:NEW_MAIN :EZACCESS);
619
620             my $foo = new(say_hi => sub {print "Hi!\n";});
621             $foo->say_hi;
622
623       ":TIED_INTERFACE"
624           This is no longer supported.  Sorry for the very short notice - if
625           you have a specific need, please let me know and I will discuss
626           your needs with you and determine whether they can be addressed in
627           a manner that doesn't require you to rewrite your code, but still
628           allows others to make use of less global control over the tied
629           interfaces used.  See "Class::Prototyped::Mirror::tiedInter‐
630           facePackage" for the preferred way of doing this.
631

"Class::Prototyped" Methods

633       new() - Construct a new "Class::Prototyped" object.
634
635       A new object is created.  If this is called on a class or object that
636       inherits from "Class::Prototyped", and "class*" is not being passed as
637       a slot in the argument list, the slot "class*" will be the first ele‐
638       ment in the inheritance list.
639
640       When called on named classes, either via the package name or via the
641       object (i.e. "MyPackage->reflect->object()"), "class*" is set to the
642       package name.  When called on an object, "class*" is set to the object
643       on which "new" was called.
644
645       The passed arguments are handed off to "addSlots".
646
647       Note that "new" calls "newCore", so if you want to override "new", but
648       want to ensure that your changes are applicable to "newPackage",
649       "clone", and "clonePackage", you may wish to override "newCore".
650
651       For instance, the following will define a new "Class::Prototyped"
652       object with two method slots and one field slot:
653
654           my $foo = Class::Prototyped->new(
655               field1 => 123,
656               sub1   => sub { print "this is sub1 in foo" },
657               sub2   => sub { print "this is sub2 in foo" },
658           );
659
660       The following will create a new "MyClass" object with one field slot
661       and with the parent object $bar at the beginning of the inheritance
662       hierarchy (just before "class*", which points to "MyClass"):
663
664           my $foo = MyClass->new(
665               field1  => 123,
666               [qw(bar* promote)] => $bar,
667           );
668
669       The following will create a new object that inherits behavior from $bar
670       with one field slot, "field1", and one parent slot, "class*", that
671       points to $bar.
672
673           my $foo = $bar->new(
674               field1  => 123,
675           );
676
677       If you want to create normal Perl objects as child objects of a
678       "Class::Prototyped" class in order to improve performance, implement
679       your own standard Perl "new" method:
680
681           Class::Prototyped->newPackage('MyClass');
682           MyClass->reflect->addSlot(
683               new => sub {
684                   my $class = shift;
685                   my $self = {};
686                   bless $self, $class;
687                   return $self;
688               }
689           );
690
691       It is still safe to use "$obj->reflect->super()" in code that runs on
692       such an object.  All other reflection will automatically return the
693       same results as inspecting the class to which the object belongs.
694
695       newPackage() - Construct a new "Class::Prototyped" object in a specific
696       package.
697
698       Just like "new", but instead of creating the new object with an arbi‐
699       trary package name (actually, not entirely arbitrary - it's generally
700       based on the hash memory address), the first argument is used as the
701       name of the package.  This creates a named class.  The same behavioral
702       rules for "class*" described above for "new" apply to "newPackage" (in
703       fact, "new" calls "newPackage").
704
705       If the package name is already in use, this method will croak.
706
707       clone() - Duplicate me
708
709       Duplicates an existing object or class and allows you to add or over‐
710       ride slots. The slot definition is the same as in new().
711
712         my $p2 = $p1->clone(
713             sub1 => sub { print "this is sub1 in p2" },
714         );
715
716       It calls "newCore" to create the new object*, so if you have overriden
717       "new", you should contemplate overriding "clone" in order to ensure
718       that behavioral changes made to "new" that would be applicable to
719       "clone" are implemented.  Or simply override "newCore".
720
721       clonePackage()
722
723       Just like "clone", but instead of creating the new object with an arbi‐
724       trary package name (actually, not entirely arbitrary - it's generally
725       based on the hash memory address), the first argument is used as the
726       name of the package.  This creates a named class.
727
728       If the package name is already in use, this method will croak.
729
730       newCore()
731
732       This implements the core functionality involved in creating a new
733       object.  The first passed parameter will be the name of the caller -
734       either "new", "newPackage", "clone", or "clonePackage".  The second
735       parameter is the name of the package if applicable (i.e. for "newPack‐
736       age" and "clonePackage") calls, "undef" if inapplicable.  The remainder
737       of the parameters are any slots to be added to the newly created
738       object/package.
739
740       If called with "new" or "newPackage", the "class*" slot will be
741       prepended to the slot list if applicable.  If called with "clone" or
742       "clonePackage", all slots on the receiver will be prepended to the slot
743       list.
744
745       If you wish to add behavior to object instantiation that needs to be
746       present in all four of the instantiators (i.e. instance tracking), it
747       may make sense to override "newCore" so that you implement the code in
748       only one place.
749
750       reflect() - Return a mirror for the object or class
751
752       The structure of an object is modified by using a mirror.  This is the
753       equivalent of calling:
754
755         Class::Prototyped::Mirror->new($foo);
756
757       destroy() - The destroy method for an object
758
759       You should never need to call this method.  However, you may want to
760       override it.  Because we had to directly specify "DESTROY" for every
761       object in order to allow safe destruction during global destruction
762       time when objects may have already destroyed packages in their @ISA, we
763       had to hook "DESTROY" for every object.  To allow the "destroy" behav‐
764       ior to be overridden, users should specify a "destroy" method for their
765       objects (by adding the slot), which will automatically be called by the
766       "Class::Prototyped::DESTROY" method after the @ISA has been cleaned up.
767
768       This method should be defined to allow inherited method calls (i.e.
769       should use ""[qw(destroy superable)]"" to define the method) and should
770       call "$self->reflect->super('destroy');" at some point in the code.
771
772       Here is a quick overview of the default destruction behavior for
773       objects:
774
775       ·   "Class::Prototyped::DESTROY" is called because it is linked into
776           the package for all objects at instantiation time
777
778       ·   All no longer existent entries are stripped from @ISA
779
780       ·   The inheritance hierarchy is searched for a "DESTROY" method that
781           is not "Class::Prototyped::DESTROY".  This "DESTROY" method is
782           stashed away for a later call.
783
784       ·   The inheritance hierarchy is searched for a "destroy" method and it
785           is called.  Note that the "Class::Prototyped::destroy" method,
786           which will either be called directly because it shows up in the
787           inheritance hierarchy or will be called indirectly through calls to
788           "$self->reflect->super('destroy');", will delete all non-parent
789           slots from the object.  It leaves parent slots alone because the
790           destructors for the parent slots should not be called until such
791           time as the destruction of the object in question is complete (oth‐
792           erwise inherited destructors might still be executing, even though
793           the object to which they belong has already been destroyed).  This
794           means that the destructors for objects referenced in non-parent
795           slots may be called, temporarily interrupting the execution
796           sequence in "Class::Prototyped::destroy".
797
798       ·   The previously stashed "DESTROY" method is called.
799
800       ·   The parent slots for the object are finally removed, thus enabling
801           the destructors for any objects referenced in those parent slots to
802           run.
803
804       ·   Final "Class::Prototyped" specific cleanup is run.
805

"Class::Prototyped::Mirror" Methods

807       These are the methods you can call on the mirror returned from a
808       "reflect" call. If you specify ":EZACCESS" in the "use Class::Proto‐
809       typed" line, "addSlot", "addSlots", "deleteSlot", "deleteSlots", "get‐
810       Slot", "getSlots", and "super" will be callable on "Class::Prototyped"
811       objects as well.
812
813       new() - Creates a new "Class::Prototyped::Mirror" object
814
815       Normally called via the "reflect" method, this can be called directly
816       to avoid using the ":REFLECT" import option for reflecting on non
817       "Class::Prototyped" based classes.
818
819       autoloadCall()
820
821       If you add an "AUTOLOAD" slot to an object, you will need to get the
822       name of the subroutine being called. "autoloadCall()" returns the name
823       of the subroutine, with the package name stripped off.
824
825       package() - Returns the name of the package for the object
826
827       object() - Returns the object itself
828
829       class() - Returns the "class*" slot for the underlying object
830
831       dump() - Returns a Data::Dumper string representing the object
832
833       addSlot() - An alias for "addSlots"
834
835       addSlots() - Add or replace slot definitions
836
837       Allows you to add or replace slot definitions in the receiver.
838
839           $p->reflect->addSlots(
840               fred        => 'this is fred',
841               doSomething => sub { print 'doing something with ' . $_[1] },
842           );
843           $p->doSomething( $p->fred );
844
845       In addition to the simple form, there is an extended syntax for speci‐
846       fying the slot.  In place of the slotname, pass an array reference com‐
847       posed like so:
848
849       "addSlots( [$slotName, $slotType, %slotAttributes] => $slotValue );"
850
851       $slotName is simply the name of the slot, including the trailing "*" if
852       it is a parent slot.  $slotType should be 'FIELD', 'METHOD', or 'PAR‐
853       ENT'.  %slotAttributes should be a list of attribute/value pairs.  It
854       is common to use qw() to reduce the amount of typing:
855
856           $p->reflect->addSlot(
857               [qw(bar FIELD)] => "this is a field",
858           );
859
860           $p->reflect->addSlot(
861               [qw(bar FIELD constant 1)] => "this is a constant field",
862           );
863
864           $p->reflect->addSlot(
865               [qw(foo METHOD)] => sub { print "normal method.\n"; },
866           );
867
868           $p->reflect->addSlot(
869               [qw(foo METHOD superable 1)] => sub { print "superable method.\n"; },
870           );
871
872           $p->reflect->addSlot(
873               [qw(parent* PARENT)] => $parent,
874           );
875
876           $p->reflect->addSlot(
877               [qw(parent2* PARENT promote 1)] => $parent2,
878           );
879
880       To make using the extended syntax a bit less cumbersome, however, the
881       following shortcuts are allowed:
882
883       ·   $slotType can be omitted.  In this case, the slot's type will be
884           determined by inspecting the slot's name (to determine if it is a
885           parent slot) and the slot's value (to determine whether it is a
886           field or method slot).  The $slotType value can, however, be used
887           to supply a reference to a code object as the value for a field
888           slot.  Note that this means that "FIELD", "METHOD", and "PARENT"
889           are not legal attribute names (since this would make parsing diffi‐
890           cult).
891
892       ·   If there is only one attribute and if the value is 1, then the
893           value can be omitted.
894
895       Using both of the above contractions, the following are valid short
896       forms for the extended syntax:
897
898           $p->reflect->addSlot(
899               [qw(bar constant)] => "this is a constant field",
900           );
901
902           $p->reflect->addSlot(
903               [qw(foo superable)] => sub { print "superable method.\n"; },
904           );
905
906           $p->reflect->addSlot(
907               [qw(parent2* promote)] => $parent2,
908           );
909
910       The currently defined slot attributes are as follows:
911
912       "FIELD" Slots
913           "constant" ("implementor")
914               When true, this defines the field slot as constant, disabling
915               the ability to modify it using the "$object->field($newValue)"
916               syntax.  The value may still be modified using the hash syntax
917               (i.e. "$object->{field} = $newValue").  This is mostly useful
918               if you have an object method call that takes parameters, but
919               you wish to replace it on a given object with a hard-coded
920               value by using a field (which makes inspecting the value of the
921               slot through "Data::Dumper" much easier than if you use a
922               "METHOD" slot to return the constant, since code objects are
923               opaque).
924
925           "autoload" ("filter", rank 50)
926               The passed value for the "FIELD" slot should be a subroutine
927               that returns the desired value.  Upon the first access, the
928               subroutine will be called, the return value hard-coded into the
929               object by adding the slot (including all otherwise specified
930               attributes), and the value then returned.  Useful for imple‐
931               menting constant slots that are costly to initialize, espe‐
932               cially those that return lists of "Class::Prototyped" objects!
933
934           "profile" ("filter", rank 80)
935               If "profile" is set to 1, increments " $Class::Prototyped::Mir‐
936               ror::PROFILE::counts->{$package}->{$slotName}" everytime the
937               slot is accessed.  If "profile" is set to 2, increments "
938               $Class::Prototyped::Mirror::PROFILE::counts->{$pack‐
939               age}->{$slotName}->{$caller}" everytime the slot is accessed,
940               where $caller is "$file ($line)".
941
942           "wantarray" ("filter", rank 90)
943               If the field specifies a reference to an array and the call is
944               in list context, dereferences the array and returns a list of
945               values.
946
947           "description" ("advisory")
948               Can be used to specify a description.  No real support for this
949               yet beyond that!
950
951       "METHOD" Slots
952           "superable" ("filter", rank 10)
953               When true, this enables the "$self->reflect->super( . . . )"
954               calls for this method slot.
955
956           "profile" ("filter", rank 90)
957               See "FIELD" slots for explanation.
958
959           "overload" ("advisory")
960               Set automatically for methods that implement operator overload‐
961               ing.
962
963           "description" ("advisory")
964               See "FIELD" slots for explanation.
965
966       "PARENT" Slots
967           "promote" ("advisory")
968               When true, this parent slot is promoted ahead of any other par‐
969               ent slots on the object.  This attribute is ephemeral - it is
970               not returned by calls to "getSlot".
971
972           "description" ("advisory")
973               See "FIELD" slots for explanation.
974
975       deleteSlot() - An alias for deleteSlots
976
977       deleteSlots() - Delete one or more of the receiver's slots by name
978
979       This will let you delete existing slots in the receiver. If those slots
980       were defined in the receiver's inheritance hierarchy, those inherited
981       definitions will now be available.
982
983           my $p1 = Class::Prototyped->new(
984               field1 => 123,
985               sub1   => sub { print "this is sub1 in p1" },
986               sub2   => sub { print "this is sub2 in p1" }
987           );
988           my $p2 = Class::Prototyped->new(
989               'parent*' => $p1,
990               sub1      => sub { print "this is sub1 in p2" },
991           );
992           $p2->sub1;    # calls $p2.sub1
993           $p2->reflect->deleteSlots('sub1');
994           $p2->sub1;    # calls $p1.sub1
995           $p2->reflect->deleteSlots('sub1');
996           $p2->sub1;    # still calls $p1.sub1
997
998       super() - Call a method defined in a parent
999
1000       The call to a method defined on a parent that is obscured by the cur‐
1001       rent one looks like so:
1002
1003           $self->reflect->super('method_name', @params);
1004
1005       slotNames() - Returns a list of all the slot names
1006
1007       This is passed an optional type parameter.  If specified, it should be
1008       one of 'FIELD', 'METHOD', or 'PARENT'.  For instance, the following
1009       will print out a list of all slots of an object:
1010
1011         print join(', ', $obj->reflect->slotNames)."\n";
1012
1013       The following would print out a list of all field slots:
1014
1015         print join(', ', $obj->reflect->slotNames('FIELD')."\n";
1016
1017       The parent slot names are returned in the same order for which inheri‐
1018       tance is done.
1019
1020       slotType() - Given a slot name, determines the type
1021
1022       This returns 'FIELD', 'METHOD', or 'PARENT'.  It croaks if the slot is
1023       not defined for that object.
1024
1025       parents() - Returns a list of all parents
1026
1027       Returns a list of all parent object (or package names) for this object.
1028
1029       allParents() - Returns a list of all parents in the hierarchy
1030
1031       Returns a list of all parent objects (or package names) in the object's
1032       hierarchy.
1033
1034       withAllParents() - Same as above, but includes self in the list
1035
1036       allSlotNames() - Returns a list of all slot names defined for the
1037       entire inheritance hierarchy
1038
1039       Note that this will return duplicate slot names if inherited slots are
1040       obscured.
1041
1042       getSlot() - Returns the requested slot
1043
1044       When called in scalar context, this returns the thing in the slot.
1045       When called in list context, it returns both the complete form of the
1046       extended syntax for specifying a slot name and the thing in the slot.
1047       There is an optional parameter that can be used to modify the format of
1048       the return value in list context.  The allowable values are:
1049
1050       ·   'default' - the extended slot syntax and the slot value are
1051           returned
1052
1053       ·   'simple' - the slot name and the slot value are returned.  Note
1054           that in this mode, there is no access to any attributes the slot
1055           may have
1056
1057       ·   'rotated' - the slot name and the following hash are returned like
1058           so:
1059
1060             $slotName => {
1061               attribs => %slotAttribs,
1062               type => $slotType,
1063               value => $slotValue
1064             },
1065
1066       The latter two options are quite useful when used in conjunction with
1067       the "getSlots" method.
1068
1069       getSlots() - Returns a list of all the slots
1070
1071       This returns a list of extended syntax slot specifiers and their values
1072       ready for sending to "addSlots".  It takes first the optional parameter
1073       passed to "slotNames" which specifies the type of slot ('FIELD',
1074       'METHOD', 'PARENT', or "undef") and then the optional parameter passed
1075       to "getSlot", which specifies the format for the return value.  If the
1076       latter is 'simple', the returned values can be passed to "addSlots",
1077       but any non-default slot attributes (i.e. "superable" or "constant")
1078       will be lost.  If the latter is 'rotated', the returned values are com‐
1079       pletely inappropriate for passing to "addSlots".  Both 'simple' and
1080       'rotated' are appropriate for assigning the return values into a hash.
1081
1082       For instance, to add all of the field slots in $bar to $foo:
1083
1084         $foo->reflect->addSlots($bar->reflect->getSlots('FIELD'));
1085
1086       To get a list of all of the slots in the 'simple' format:
1087
1088         my %barSlots = $bar->reflect->getSlots(undef, 'simple');
1089
1090       To get a list of all of the superable method slots in the 'rotated'
1091       format:
1092
1093         my %barMethods = $bar->reflect->getSlots('METHOD', 'rotated');
1094         foreach my $slotName (%barMethods) {
1095           delete $barMethods{$slotName}
1096             unless $barMethods{$slotName}->{attribs}->{superable};
1097         }
1098
1099       promoteParents() - This changes the ordering of the parent slots
1100
1101       This expects a list of parent slot names.  There should be no dupli‐
1102       cates and all of the parent slot names should be already existing par‐
1103       ent slots on the object.  These parent slots will be moved forward in
1104       the hierarchy in the order that they are passed.  Unspecified parent
1105       slots will retain their current positions relative to other unspecified
1106       parent slots, but as a group they will be moved to the end of the hier‐
1107       archy.
1108
1109       tiedInterfacePackage() - This specifies the tied interface package
1110
1111       This allows you to specify the sort of tied interface you wish to offer
1112       when code accesses the object as a hash reference.  If no parameter is
1113       passed, this will return the current tied interface package active for
1114       the object.  If a parameter is passed, it should specify either the
1115       package name or an alias.  The currently known aliases are:
1116
1117       default
1118           This specifies "Class::Prototyped::Tied::Default" as the tie class.
1119           The default behavior is to allow access to existing fields, but
1120           attempts to create fields, access methods, or delete slots will
1121           croak.  This is the tie class used by "Class::Prototyped" (unless
1122           you do something very naughty and call "Class::Proto‐
1123           typed->reflect->tiedInterfacePackage($not_default)"), and as such
1124           is the fallback behavior for classes and objects if they don't get
1125           a different value from their inheritance.
1126
1127       autovivify
1128           This specifies "Class::Prototyped::Tied::AutoVivify" as the tie
1129           class.  The behavior of this package allows access to existing
1130           fields, will automatically create field slots if they don't exist,
1131           and will allow deletion of field slots.  Attempts to access or
1132           delete method or parent slots will croak.
1133
1134       Calls to "new" and "clone" will use the tied interface in use on the
1135       existing object/package.  When "reflect" is called for the first time
1136       on a class package, it will use the tied interface of its first parent
1137       class (i.e.  $ISA[0]).  If that package has not yet had "reflect"
1138       called on it, it will check its parent, and so on and so forth.  If
1139       none of the packages in the primary inheritance fork have been
1140       reflected upon, the value for "Class::Prototyped" will be used, which
1141       should be "default".
1142
1143       defaultAttributes() - get and set default attributes
1144
1145       This isn't particularly pretty.  The general syntax looks something
1146       like:
1147
1148           my $temp = MyClass->reflect->defaultAttributes;
1149           $temp->{METHOD}->{superable} = 1;
1150           MyClass->reflect->defaultAttributes($temp);
1151
1152       The return value from "defaultAttributes" is a hash with the keys
1153       'FIELD', 'METHOD', and 'PARENT'.  The values are either "undef" or hash
1154       references consisting of the attributes and their default values.  Mod‐
1155       ify the data structure as desired and pass it back to "defaultAt‐
1156       tributes" to change the default attributes for that object or class.
1157       Note that default attributes are not inherited dynamically - the inher‐
1158       itance occurs when a new object is created, but from that point on
1159       changes to a parent object are not inherited by the child.  Global
1160       changes can be effected by modifying the "defaultAttributes" for
1161       "Class::Prototyped" in a sufficiently early "BEGIN" block.  Note that
1162       making global changes like this is "not" recommended for production
1163       modules as it may interfere with other modules that rely upon
1164       "Class::Prototyped".
1165
1166       wrap()
1167
1168       unwrap()
1169
1170       delegate()
1171
1172       delegate name => slot name can be string, regex, or array of same.
1173       slot can be slot name, or object, or 2-element array with slot name or
1174       object and method name.  You can delegate to a parent.
1175
1176       include() - include a package or external file
1177
1178       You can "require" an arbitrary file in the namespace of an object or
1179       class without adding to the parents using "include()" :
1180
1181         $foo->include( 'xx.pl' );
1182
1183       will include whatever is in xx.pl. Likewise for modules:
1184
1185         $foo->include( 'MyModule' );
1186
1187       will search along your @INC path for "MyModule.pm" and include it.
1188
1189       You can specify a second parameter that will be the name of a subrou‐
1190       tine that you can use in your included code to refer to the object into
1191       which the code is being included (as long as you don't change packages
1192       in the included code). The subroutine will be removed after the
1193       include, so don't call it from any subroutines defined in the included
1194       code.
1195
1196       If you have the following in "File.pl":
1197
1198           sub b {'xxx.b'}
1199
1200           sub c { return thisObject(); }    # DON'T DO THIS!
1201
1202           thisObject()->reflect->addSlots(
1203               'parent*' => 'A',
1204               d         => 'added.d',
1205               e         => sub {'xxx.e'},
1206           );
1207
1208       And you include it using:
1209
1210           $mirror->include('File.pl', 'thisObject');
1211
1212       Then the "addSlots" will work fine, but if sub "c" is called, it won't
1213       find "thisObject()".
1214

AUTHOR

1216       Written by Ned Konz, perl@bike-nomad.com and Toby Ovod-Everett,
1217       toby@ovod-everett.org. 5.005_03 porting by chromatic.
1218
1219       Toby Ovod-Everett is currently maintaining the package.
1220

LICENSE

1222       Copyright 2001-2004 Ned Konz and Toby Ovod-Everett.  All rights
1223       reserved. This program is free software; you can redistribute it and/or
1224       modify it under the same terms as Perl itself.
1225

SEE ALSO

1227       Class::SelfMethods
1228
1229       Class::Object
1230
1231       Class::Classless
1232
1233
1234
1235perl v5.8.8                       2007-04-30              Class::Prototyped(3)
Impressum