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
51       programming in Perl. You can provide different subroutines for each
52       object, and also have objects inherit their behavior and state from
53       another 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       This module requires "Module::Build 0.24" to use the automated
61       installation procedures.  With "Module::Build" installed:
62
63         Build.PL
64         perl build test
65         perl build install
66
67       It can be installed under ActivePerl for Win32 by downloading the PPM
68       from CPAN (the file has the extension ".ppm.zip").  To install,
69       download the ".ppm.zip" file, uncompress it, and execute:
70
71         ppm install Class-Prototyped.ppd
72
73       The module can also be installed manually by copying
74       "lib/Class/Prototyped.pm" to "perl/site/lib/Class/Prototyped.pm" (along
75       with "Graph.pm" if you want it).
76

WHEN TO USE THIS MODULE

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

CONCEPTS

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

PERFORMANCE NOTES

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

IMPORT OPTIONS

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

"Class::Prototyped" Methods

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

"Class::Prototyped::Mirror" Methods

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

AUTHOR

1176       Written by Ned Konz, perl@bike-nomad.com and Toby Ovod-Everett,
1177       toby@ovod-everett.org. 5.005_03 porting by chromatic.
1178
1179       Toby Ovod-Everett is currently maintaining the package.
1180

LICENSE

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

SEE ALSO

1187       Class::SelfMethods
1188
1189       Class::Object
1190
1191       Class::Classless
1192
1193
1194
1195perl v5.28.1                      2019-02-02              Class::Prototyped(3)
Impressum