• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

examples/H03-May-2022-1711

lib/Class/H28-Aug-2013-3,0041,345

perf/H28-Aug-2013-267118

t/H28-Aug-2013-2,0551,700

Build.PLH A D28-Aug-20131.1 KiB4940

ChangesH A D28-Aug-201312.1 KiB300280

MANIFESTH A D28-Aug-2013426 2827

META.jsonH A D28-Aug-20131.8 KiB6564

META.ymlH A D28-Aug-20131.2 KiB4342

Makefile.PLH A D28-Aug-2013290 1311

READMEH A D28-Aug-201350.7 KiB1,180928

README

1NAME
2    "Class::Prototyped" - Fast prototype-based OO programming in Perl
3
4SYNOPSIS
5        use strict;
6        use Class::Prototyped ':EZACCESS';
7
8        $, = ' '; $\ = "\n";
9
10        my $p = Class::Prototyped->new(
11          field1 => 123,
12          sub1   => sub { print "this is sub1 in p" },
13          sub2   => sub { print "this is sub2 in p" }
14        );
15
16        $p->sub1;
17        print $p->field1;
18        $p->field1('something new');
19        print $p->field1;
20
21        my $p2 = Class::Prototyped->new(
22          'parent*' => $p,
23          field2    => 234,
24          sub2      => sub { print "this is sub2 in p2" }
25        );
26
27        $p2->sub1;
28        $p2->sub2;
29        print ref($p2), $p2->field1, $p2->field2;
30        $p2->field1('and now for something different');
31        print ref($p2), $p2->field1;
32
33        $p2->addSlots( sub1 => sub { print "this is sub1 in p2" } );
34        $p2->sub1;
35
36        print ref($p2), "has slots", $p2->reflect->slotNames;
37
38        $p2->reflect->include( 'xx.pl' ); # includes xx.pl in $p2's package
39        print ref($p2), "has slots", $p2->reflect->slotNames;
40        $p2->aa();    # calls aa from included file xx.pl
41
42        $p2->deleteSlots('sub1');
43        $p2->sub1;
44
45DESCRIPTION
46    This package provides for efficient and simple prototype-based
47    programming in Perl. You can provide different subroutines for each
48    object, and also have objects inherit their behavior and state from
49    another object.
50
51    The structure of an object is inspected and modified through *mirrors*,
52    which are created by calling "reflect" on an object or class that
53    inherits from "Class::Prototyped".
54
55  Installation instructions
56    This module requires "Module::Build 0.24" to use the automated
57    installation procedures. With "Module::Build" installed:
58
59      Build.PL
60      perl build test
61      perl build install
62
63    It can be installed under ActivePerl for Win32 by downloading the PPM
64    from CPAN (the file has the extension ".ppm.zip"). To install, download
65    the ".ppm.zip" file, uncompress it, and execute:
66
67      ppm install Class-Prototyped.ppd
68
69    The module can also be installed manually by copying
70    "lib/Class/Prototyped.pm" to "perl/site/lib/Class/Prototyped.pm" (along
71    with "Graph.pm" if you want it).
72
73WHEN TO USE THIS MODULE
74    When I reach for "Class::Prototyped", it's generally because I really
75    need it. When the cleanest way of solving a problem is for the code that
76    uses a module to subclass from it, that is generally a sign that
77    "Class::Prototyped" would be of use. If you find yourself avoiding the
78    problem by passing anonymous subroutines as parameters to the "new"
79    method, that's another good sign that you should be using prototype
80    based programming. If you find yourself storing anonymous subroutines in
81    databases, configuration files, or text files, and then writing
82    infrastructure to handle calling those anonymous subroutines, that's yet
83    another sign. When you expect the people using your module to want to
84    change the behavior, override subroutines, and so forth, that's a sign.
85
86CONCEPTS
87  Slots
88    "Class::Prototyped" borrows very strongly from the language Self (see
89    http://www.sun.com/research/self for more information). The core concept
90    in Self is the concept of a slot. Think of slots as being entries in a
91    hash, except that instead of just pointing to data, they can point to
92    objects, code, or parent objects.
93
94    So what happens when you send a message to an object (that is to say,
95    you make a method call on the object)? First, Perl looks for that slot
96    in the object. If it can't find that slot in the object, it searches for
97    that slot in one of the object's parents (which we'll come back to
98    later). Once it finds the slot, if the slot is a block of code, it
99    evaluates the code and returns the return value. If the slot references
100    data, it returns that data. If you assign to a data slot (through a
101    method call), it modifies the data.
102
103    Distinguishing data slots and method slots is easy - the latter are
104    references to code blocks, the former are not. Distinguishing parent
105    slots is not so easy, so instead a simple naming convention is used. If
106    the name of the slot ends in an asterisk, the slot is a parent slot. If
107    you have programmed in Self, this naming convention will feel very
108    familiar.
109
110  Reflecting
111    In Self, to examine the structure of an object, you use a mirror. Just
112    like using his shield as a mirror enabled Perseus to slay Medusa,
113    holding up a mirror enables us to look upon an object's structure
114    without name space collisions.
115
116    Once you have a mirror, you can add and delete slots like so:
117
118        my $cp = Class::Prototyped->new();
119        my $mirror = $cp->reflect();
120        $mirror->addSlots(
121          field1 => 'foo',
122          sub1   => sub {
123            print "this is sub1 printing field1: '".$_[0]->field1."'\n";
124          },
125        );
126
127        $mirror->deleteSlot('sub1');
128
129    In addition, there is a more verbose syntax for "addSlots" where the
130    slot name is replaced by an anonymous array - this is most commonly used
131    to control the slot attributes.
132
133        $cp->reflect->addSlot(
134          [qw(field1 FIELD)] => 'foo',
135          [qw(sub1 METHOD)]  => sub { print "hi there.\n"; },
136        );
137
138    Because the mirror methods "super", "addSlot"("s"), "deleteSlot"("s"),
139    and "getSlot"("s") are called frequently on objects, there is an import
140    keyword ":EZACCESS" that adds methods to the object space that call the
141    appropriate reflected variants.
142
143  Slot Attributes
144    Slot attributes allow the user to specify additional information and
145    behavior relating to a specific slot in an extensible manner. For
146    instance, one might want to mark a specific field slot as constant or to
147    attach a description to a given slot.
148
149    Slot attributes are divided up in two ways. The first is by the type of
150    slot - "FIELD", "METHOD", or "PARENT". Some slot attributes apply to all
151    three, some to just two, and some to only one. The second division is on
152    the type of slot attribute:
153
154    implementor
155        These are responsible for implementing the behavior of a slot. An
156        example is a "FIELD" slot with the attribute "constant". A slot is
157        only allowed one implementor. All slot types have a default
158        implementor. For "FIELD" slots, it is a read-write scalar. For
159        "METHOD" slots, it is the passed anonymous subroutine. For "PARENT"
160        slots, "implementor" and "filter" slot attributes don't really make
161        sense.
162
163    filter
164        These filter access to the "implementor". The quintessential example
165        is the "profile" attribute. When set, this increments a counter in
166        $Class::Prototyped::Mirror::PROFILE::counts every time the
167        underlying "FIELD" or "METHOD" is accessed. Filter attributes can be
168        stacked, so each attribute is assigned a rank with lower values
169        being closer to the "implementor" and higher values being closer to
170        the caller.
171
172    advisory
173        These slot attributes serve one of two purposes. They can be used to
174        store information about the slot (i.e. "description" attributes),
175        and they can be used to pass information to the "addSlots" method
176        (i.e. the "promote" attribute, which can be used to promote a new
177        "PARENT" slot ahead of all the existing "PARENT" slots).
178
179    There is currently no formal interface for creating your own attributes
180    - if you feel the need for new attributes, please contact the maintainer
181    first to see if it might make sense to add the new attribute to
182    "Class::Prototyped". If not, the contact might provide enough impetus to
183    define a formal interface. The attributes are currently defined in
184    $Class::Prototyped::Mirror::attributes.
185
186    Finally, see the "defaultAttributes" method for information about
187    setting default attributes. This can be used, for instance, to turn on
188    profiling everywhere.
189
190  Classes vs. Objects
191    In Self, everything is an object and there are no classes at all. Perl,
192    for better or worse, has a class system based on packages. We decided
193    that it would be better not to throw out the conventional way of
194    structuring inheritance hierarchies, so in "Class::Prototyped", classes
195    are first-class objects.
196
197    However, objects are not first-class classes. To understand this
198    dichotomy, we need to understand that there is a difference between the
199    way "classes" and the way "objects" are expected to behave. The central
200    difference is that "classes" are expected to persist whether or not that
201    are any references to them. If you create a class, the class exists
202    whether or not it appears in anyone's @ISA and whether or not there are
203    any objects in it. Once a class is created, it persists until the
204    program terminates.
205
206    Objects, on the other hand, should follow the normal behaviors of
207    reference-counted destruction - once the number of references to them
208    drops to zero, they should miraculously disappear - the memory they used
209    needs to be returned to Perl, their "DESTROY" methods need to be called,
210    and so forth.
211
212    Since we don't require this behavior of classes, it's easy to have a way
213    to get from a package name to an object - we simply stash the object
214    that implements the class in
215    $Class::Prototyped::Mirror::objects{$package}. But we can't do this for
216    objects, because if we do the object will persist forever because that
217    reference will always exist.
218
219    Weak references would solve this problem, but weak references are still
220    considered alpha and unsupported ("$WeakRef::VERSION = 0.01"), and we
221    didn't want to make "Class::Prototyped" dependent on such a module.
222
223    So instead, we differentiate between classes and objects. In a nutshell,
224    if an object has an explicit package name (*i.e.* something other than
225    the auto-generated one), it is considered to be a class, which means it
226    persists even if the object goes out of scope.
227
228    To create such an object, use the "newPackage" method, like so (the
229    encapsulating block exists solely to demonstrate that classes are not
230    scoped):
231
232        {
233          my $object = Class::Prototyped->newPackage('MyClass',
234              field => 1,
235              double => sub {$_[0]->field*2}
236            );
237        }
238
239        print MyClass->double,"\n";
240
241    Notice that the class persists even though $object goes out of scope. If
242    $object were created with an auto-generated package, that would not be
243    true. Thus, for instance, it would be a very, very, very bad idea to add
244    the package name of an object as a parent to another object - when the
245    first object goes out of scope, the package will disappear, but the
246    second object will still have it in it's @ISA.
247
248    Except for the crucial difference that you should never, ever, ever make
249    use of the package name for an object for any purpose other than
250    printing it to the screen, objects and classes are simply different ways
251    of inspecting the same entity.
252
253    To go from an object to a package, you can do one of the following:
254
255        $package = ref($object);
256        $package = $object->reflect->package;
257
258    The two are equivalent, although the first is much faster. Just
259    remember, if $object is in an auto-generated package, don't do anything
260    with that $package but print it.
261
262    To go from a package to an object, you do this:
263
264        $object = $package->reflect->object;
265
266    Note that $package is simple the name of the package - the following
267    code works perfectly:
268
269        $object = MyClass->reflect->object;
270
271    But keep in mind that $package has to be a class, not an auto-generated
272    package name for an object.
273
274  Class Manipulation
275    This lets us have tons of fun manipulating classes at run time. For
276    instance, if you wanted to add, at run-time, a new method to the
277    "MyClass" class? Assuming that the "MyClass" inherits from
278    "Class::Prototyped" or that you have specified ":REFLECT" on the "use
279    Class::Prototyped" call, you simply write:
280
281        MyClass->reflect->addSlot(myMethod => sub {print "Hi there\n"});
282
283    If you want to access a class that doesn't inherit from
284    "Class::Prototyped", and you want to avoid specifying ":REFLECT" (which
285    adds "reflect" to the "UNIVERSAL" package), you can make the call like
286    so:
287
288        my $mirror = Class::Prototyped::Mirror->new('MyClass');
289        $mirror->addSlot(myMethod => sub {print "Hi there\n"});
290
291    Just as you can "clone" objects, you can "clone" classes that are
292    derived from "Class::Prototyped". This creates a new object that has a
293    copy of all of the slots that were defined in the class. Note that if
294    you simply want to be able to use "Data::Dumper" on a class, calling
295    "MyClass->reflect->object" is the preferred approach. Even easier would
296    be to use the "dump" mirror method.
297
298    The code that implements reflection on classes automatically creates
299    slot names for package methods as well as parent slots for the entries
300    in @ISA. This means that you can code classes like you normally do - by
301    doing the inheritance in @ISA and writing package methods.
302
303    If you manually add subroutines to a package at run-time and want the
304    slot information updated properly (although this really should be done
305    via the "addSlots" mechanism, but maybe you're twisted:), you should do
306    something like:
307
308        $package->reflect->_vivified_methods(0);
309        $package->reflect->_autovivify_methods;
310
311  Parent Slots
312    Adding parent slots is no different than adding normal slots - the
313    naming scheme takes care of differentiating.
314
315    Thus, to add $foo as a parent to $bar, you write:
316
317        $bar->reflect->addSlot('fooParent*' => $foo);
318
319    However, keeping with our concept of classes as first class objects, you
320    can also write the following:
321
322        $bar->reflect->addSlot('mixIn*' => 'MyMix::Class');
323
324    It will automatically require the module in the namespace of $bar and
325    make the module a parent of the object. This can load a module from disk
326    if needed.
327
328    If you're lazy, you can add parents without names like so:
329
330        $bar->reflect->addSlot('*' => $foo);
331
332    The slots will be automatically named for the package passed in - in the
333    case of "Class::Prototyped" objects, the package is of the form
334    "PKG0x12345678". In the following example, the parent slot will be named
335    "MyMix::Class*".
336
337        $bar->reflect->addSlot('*' => 'MyMix::Class');
338
339    Parent slots are added to the inheritance hierarchy in the order that
340    they were added. Thus, in the following code, slots that don't exist in
341    $foo are looked up in $fred (and all of its parent slots) before being
342    looked up in $jill.
343
344        $foo->reflect->addSlots('fred*' => $fred, 'jill*' => $jill);
345
346    Note that "addSlot" and "addSlots" are identical - the variants exist
347    only because it looks ugly to add a single slot by calling "addSlots".
348
349    If you need to reorder the parent slots on an object, look at
350    "promoteParents". That said, there's a shortcut for prepending a slot to
351    the inheritance hierarchy. Simply define 'promote' as a slot attribute
352    using the extended slot syntax.
353
354    Finally, in keeping with our principle that classes are first-class
355    object, the inheritance hierarchy of classes can be modified through
356    "addSlots" and "deleteSlots", just like it can for objects. The
357    following code adds the $foo object as a parent of the "MyClass" class,
358    prepending it to the inheritance hierarchy:
359
360        MyClass->reflect->addSlots([qw(foo* promote)] => $foo);
361
362  Operator Overloading
363    In "Class::Prototyped", you do operator overloading by adding slots with
364    the right name. First, when you do the "use" on "Class::Prototyped",
365    make sure to pass in ":OVERLOAD" so that the operator overloading
366    support is enabled.
367
368    Then simply pass the desired methods in as part of the object creation
369    like so:
370
371        $foo = Class::Prototyped->new(
372            value => 3,
373            '""'  => sub { my $self = shift; $self->value( $self->value + 1 ) },
374        );
375
376    This creates an object that increments its field "value" by one and
377    returns that incremented value whenever it is stringified.
378
379    Since there is no way to find out which operators are overloaded, if you
380    add overloading to a *class* through the use of "use overload", that
381    behavior will not show up as slots when reflecting on the class.
382    However, "addSlots" does work for adding operator overloading to
383    classes. Thus, the following code does what is expected:
384
385        Class::Prototyped->newPackage('MyClass');
386        MyClass->reflect->addSlots(
387            '""' => sub { my $self = shift; $self->value( $self->value + 1 ) },
388        );
389
390        $foo = MyClass->new( value => 2 );
391        print $foo, "\n";
392
393  Object Class
394    The special parent slot "class*" is used to indicate object class. When
395    you create "Class::Prototyped" objects by calling
396    "Class::Prototyped->new()", the "class*" slot is not set. If, however,
397    you create objects by calling "new" on a class or object that inherits
398    from "Class::Prototyped", the slot "class*" points to the package name
399    if "new" was called on a named class, or the object if "new" was called
400    on an object.
401
402    The value of this slot can be returned quite easily like so:
403
404        $foo->reflect->class;
405
406  Calling Inherited Methods
407    Methods (and fields) inherited from prototypes or classes are *not*
408    generally available using the usual Perl "$self->SUPER::something()"
409    mechanism.
410
411    The reason for this is that "SUPER::something" is hardcoded to the
412    package in which the subroutine (anonymous or otherwise) was defined.
413    For the vast majority of programs, this will be "main::", and thus
414    "SUPER::" will look in @main::ISA (not a very useful place to look).
415
416    To get around this, a very clever wrapper can be automatically placed
417    around your subroutine that will automatically stash away the package to
418    which the subroutine is attached. From within the subroutine, you can
419    use the "super" mirror method to make an inherited call. However,
420    because we'd rather not write code that attempts to guess as to whether
421    or not the subroutine uses the "super" construct, you have to tell
422    "addSlots" that the subroutine needs to have this wrapper placed around
423    it. To do this, simply use the extended "addSlots" syntax (see the
424    method description for more information) and pass in the slot attribute
425    'superable'. The following examples use the minimalist form of the
426    extended syntax.
427
428    For instance, the following code will work:
429
430        use Class::Prototyped;
431
432        my $p1 = Class::Prototyped->new(
433            method => sub { print "this is method in p1\n" },
434        );
435
436        my $p2 = Class::Prototyped->new(
437            '*'                     => $p1,
438            [qw(method superable)]' => sub {
439                print "this is method in p2 calling method in p1: ";
440                $_[0]->reflect->super('method');
441            },
442        );
443
444    To make things easier, if you specify ":EZACCESS" during the import,
445    "super" can be called directly on an object rather than through its
446    mirror.
447
448    The other thing of which you need to be aware is copying methods from
449    one object to another. The proper way to do this is like so:
450
451        $foo->reflect->addSlot($bar->reflect->getSlot('method'));
452
453    When the "getSlot" method is called in an array context, it returns both
454    the complete format for the slot identifier and the slot. This ensures
455    that slot attributes are passed along, including the "superable"
456    attribute.
457
458    Finally, to help protect the code, the "super" method is smart enough to
459    determine whether it was called within a wrapped subroutine. If it
460    wasn't, it croaks indicating that the method should have had the
461    "superable" attribute set when it was added. If you wish to disable this
462    checking (which will improve the performance of your code, of course,
463    but could result in very hard to trace bugs if you haven't been
464    careful), see the import option ":SUPER_FAST".
465
466PERFORMANCE NOTES
467    It is important to be aware of where the boundaries of prototyped based
468    programming lie, especially in a language like Perl that is not
469    optimized for it. For instance, it might make sense to implement every
470    field in a database as an object. Those field objects would in turn be
471    attached to a record class. All of those might be implemented using
472    "Class::Prototyped". However, it would be very inefficient if every
473    record that got read from the database was stored in a
474    "Class::Prototyped" based object (unless, of course, you are storing
475    code in the database). In that situation, it is generally good to choke
476    off the prototype-based behavior for the individual record objects. For
477    best performance, it is important to confine "Class::Prototyped" to
478    those portions of the code where behavior is mutable from outside of the
479    module. See the documentation for the "new" method of
480    "Class::Prototyped" for more information about choking off
481    "Class::Prototyped" behavior.
482
483    There are a number of performance hits when using "Class::Prototyped",
484    relative to using more traditional OO code. It is important to note that
485    these generally lie in the instantiation and creation of classes and
486    objects and not in the actual use of them. The scripts in the "perf"
487    directory were designed for benchmarking some of this material.
488
489  Class Instantiation
490    The normal way of creating a class is like this:
491
492        package Pack_123;
493        sub a {"hi";}
494        sub b {"hi";}
495        sub c {"hi";}
496        sub d {"hi";}
497        sub e {"hi";}
498
499    The most efficient way of doing that using "proper" "Class::Prototyped"
500    methodology looks like this:
501
502        Class::Prototyped->newPackage("Pack_123");
503        push(@P_123::slots, a => sub {"hi";});
504        push(@P_123::slots, b => sub {"hi";});
505        push(@P_123::slots, c => sub {"hi";});
506        push(@P_123::slots, d => sub {"hi";});
507        push(@P_123::slots, e => sub {"hi";});
508        Pack_123->reflect->addSlots(@P_123::slots);
509
510    This approach ensures that the new package gets the proper default
511    attributes and that the slots are created through "addSlots", thus
512    ensuring that default attributes are properly implemented. It avoids
513    multiple calls to "->reflect->addSlot", though, which improves
514    performance. The idea behind pushing the slots onto an array is that it
515    enables one to intersperse code with POD, since POD is not permitted
516    inside of a single Perl statement.
517
518    On a Pent 4 1.8GHz machine, the normal code runs in 120 usec, whereas
519    the "Class::Prototyped" code runs in around 640 usec, or over 5 times
520    slower. A straight call to "addSlots" with all five methods runs in
521    around 510 usec. Code that creates the package and the mirror without
522    adding slots runs in around 135 usec, so we're looking at an overhead of
523    less than 100 usec per slot. In a situation where the "compile" time
524    dominates the "execution" time (I'm using those terms loosely as much of
525    what happens in "Class::Prototyped" is technically execution time, but
526    it is activity that traditionally would happen at compile time),
527    "Class::Prototyped" might prove to be too much overhead. On the
528    otherhand, you may find that demand loading can cut much of that
529    overhead and can be implemented less painfully than might otherwise be
530    thought.
531
532  Object Instantiation
533    There is no need to even compare here. Blessing a hash into a class
534    takes less than 2 usec. Creating a new "Class::Prototyped" object takes
535    at least 60 or 70 times longer. The trick is to avoid creating
536    unnecessary "Class::Prototyped" objects. If you know that all 10,000
537    database records are going to inherit all of their behavior from the
538    parent class, there is no point in creating 10,000 packages and all the
539    attendant overhead. The "new" method for "Class::Prototyped"
540    demonstrates how to ensure that those state objects are created as
541    normal Perl objects.
542
543  Method Calls
544    The good news is that method calls are just as fast as normal Perl
545    method calls, inherited or not. This is because the existing Perl OO
546    machinery has been hijacked in "Class::Prototyped". The exception to
547    this is if "filter" slot attributes have been used, including
548    "wantarray", "superable", and "profile". In that situation, the added
549    overhead is that for a normal Perl subroutine call (which is faster than
550    a method call because it is a static binding)
551
552  Instance Variable Access
553    The hash interface is not particularly fast, and neither is it good
554    programming practice. Using the method interface to access fields is
555    just as fast, however, as using normal getter/setter methods.
556
557IMPORT OPTIONS
558    ":OVERLOAD"
559        This configures the support in "Class::Prototyped" for using
560        operator overloading.
561
562    ":REFLECT"
563        This defines "UNIVERSAL::reflect" to return a mirror for any class.
564        With a mirror, you can manipulate the class, adding or deleting
565        methods, changing its inheritance hierarchy, etc.
566
567    ":EZACCESS"
568        This adds the methods "addSlot", "addSlots", "deleteSlot",
569        "deleteSlots", "getSlot", "getSlots", and "super" to
570        "Class::Prototyped".
571
572        This lets you write:
573
574          $foo->addSlot(myMethod => sub {print "Hi there\n"});
575
576        instead of having to write:
577
578          $foo->reflect->addSlot(myMethod => sub {print "Hi there\n"});
579
580        The other methods in "Class::Prototyped::Mirror" should be accessed
581        through a mirror (otherwise you'll end up with way too much name
582        space pollution for your objects:).
583
584        Note that it is bad form for published modules to use ":EZACCESS" as
585        you are polluting everyone else's namespace as well. If you really
586        want ":EZACCESS" for code you plan to publish, contact the
587        maintainer and we'll see what we can about creating a variant of
588        ":EZACCESS" that adds the shortcut methods to a single class. Note
589        that using ":EZACCESS" to do "$obj->addSlot()" is actually slower
590        than doing "$obj->reflect->addSlot()".
591
592    ":SUPER_FAST"
593        Switches over to the fast version of "super" that doesn't check to
594        see whether slots that use inherited calls were defined as
595        superable.
596
597    ":NEW_MAIN"
598        Creates a "new" function in "main::" that creates new
599        "Class::Prototyped" objects. Thus, you can write code like:
600
601          use Class::Prototyped qw(:NEW_MAIN :EZACCESS);
602
603          my $foo = new(say_hi => sub {print "Hi!\n";});
604          $foo->say_hi;
605
606    ":TIED_INTERFACE"
607        This is no longer supported. Sorry for the very short notice - if
608        you have a specific need, please let me know and I will discuss your
609        needs with you and determine whether they can be addressed in a
610        manner that doesn't require you to rewrite your code, but still
611        allows others to make use of less global control over the tied
612        interfaces used. See
613        "Class::Prototyped::Mirror::tiedInterfacePackage" for the preferred
614        way of doing this.
615
616"Class::Prototyped" Methods
617  new() - Construct a new "Class::Prototyped" object.
618    A new object is created. If this is called on a class or object that
619    inherits from "Class::Prototyped", and "class*" is not being passed as a
620    slot in the argument list, the slot "class*" will be the first element
621    in the inheritance list.
622
623    When called on named classes, either via the package name or via the
624    object (i.e. "MyPackage->reflect->object()"), "class*" is set to the
625    package name. When called on an object, "class*" is set to the object on
626    which "new" was called.
627
628    The passed arguments are handed off to "addSlots".
629
630    Note that "new" calls "newCore", so if you want to override "new", but
631    want to ensure that your changes are applicable to "newPackage",
632    "clone", and "clonePackage", you may wish to override "newCore".
633
634    For instance, the following will define a new "Class::Prototyped" object
635    with two method slots and one field slot:
636
637        my $foo = Class::Prototyped->new(
638            field1 => 123,
639            sub1   => sub { print "this is sub1 in foo" },
640            sub2   => sub { print "this is sub2 in foo" },
641        );
642
643    The following will create a new "MyClass" object with one field slot and
644    with the parent object $bar at the beginning of the inheritance
645    hierarchy (just before "class*", which points to "MyClass"):
646
647        my $foo = MyClass->new(
648            field1  => 123,
649            [qw(bar* promote)] => $bar,
650        );
651
652    The following will create a new object that inherits behavior from $bar
653    with one field slot, "field1", and one parent slot, "class*", that
654    points to $bar.
655
656        my $foo = $bar->new(
657            field1  => 123,
658        );
659
660    If you want to create normal Perl objects as child objects of a
661    "Class::Prototyped" class in order to improve performance, implement
662    your own standard Perl "new" method:
663
664        Class::Prototyped->newPackage('MyClass');
665        MyClass->reflect->addSlot(
666            new => sub {
667                my $class = shift;
668                my $self = {};
669                bless $self, $class;
670                return $self;
671            }
672        );
673
674    It is still safe to use "$obj->reflect->super()" in code that runs on
675    such an object. All other reflection will automatically return the same
676    results as inspecting the class to which the object belongs.
677
678  newPackage() - Construct a new "Class::Prototyped" object in a
679specific package.
680    Just like "new", but instead of creating the new object with an
681    arbitrary package name (actually, not entirely arbitrary - it's
682    generally based on the hash memory address), the first argument is used
683    as the name of the package. This creates a named class. The same
684    behavioral rules for "class*" described above for "new" apply to
685    "newPackage" (in fact, "new" calls "newPackage").
686
687    If the package name is already in use, this method will croak.
688
689  clone() - Duplicate me
690    Duplicates an existing object or class and allows you to add or override
691    slots. The slot definition is the same as in new().
692
693      my $p2 = $p1->clone(
694          sub1 => sub { print "this is sub1 in p2" },
695      );
696
697    It calls "newCore" to create the new object*, so if you have overriden
698    "new", you should contemplate overriding "clone" in order to ensure that
699    behavioral changes made to "new" that would be applicable to "clone" are
700    implemented. Or simply override "newCore".
701
702  clonePackage()
703    Just like "clone", but instead of creating the new object with an
704    arbitrary package name (actually, not entirely arbitrary - it's
705    generally based on the hash memory address), the first argument is used
706    as the name of the package. This creates a named class.
707
708    If the package name is already in use, this method will croak.
709
710  newCore()
711    This implements the core functionality involved in creating a new
712    object. The first passed parameter will be the name of the caller -
713    either "new", "newPackage", "clone", or "clonePackage". The second
714    parameter is the name of the package if applicable (i.e. for
715    "newPackage" and "clonePackage") calls, "undef" if inapplicable. The
716    remainder of the parameters are any slots to be added to the newly
717    created object/package.
718
719    If called with "new" or "newPackage", the "class*" slot will be
720    prepended to the slot list if applicable. If called with "clone" or
721    "clonePackage", all slots on the receiver will be prepended to the slot
722    list.
723
724    If you wish to add behavior to object instantiation that needs to be
725    present in all four of the instantiators (i.e. instance tracking), it
726    may make sense to override "newCore" so that you implement the code in
727    only one place.
728
729  reflect() - Return a mirror for the object or class
730    The structure of an object is modified by using a mirror. This is the
731    equivalent of calling:
732
733      Class::Prototyped::Mirror->new($foo);
734
735  destroy() - The destroy method for an object
736    You should never need to call this method. However, you may want to
737    override it. Because we had to directly specify "DESTROY" for every
738    object in order to allow safe destruction during global destruction time
739    when objects may have already destroyed packages in their @ISA, we had
740    to hook "DESTROY" for every object. To allow the "destroy" behavior to
741    be overridden, users should specify a "destroy" method for their objects
742    (by adding the slot), which will automatically be called by the
743    "Class::Prototyped::DESTROY" method after the @ISA has been cleaned up.
744
745    This method should be defined to allow inherited method calls (*i.e.*
746    should use ""[qw(destroy superable)]"" to define the method) and should
747    call "$self->reflect->super('destroy');" at some point in the code.
748
749    Here is a quick overview of the default destruction behavior for
750    objects:
751
752    *   "Class::Prototyped::DESTROY" is called because it is linked into the
753        package for all objects at instantiation time
754
755    *   All no longer existent entries are stripped from @ISA
756
757    *   The inheritance hierarchy is searched for a "DESTROY" method that is
758        not "Class::Prototyped::DESTROY". This "DESTROY" method is stashed
759        away for a later call.
760
761    *   The inheritance hierarchy is searched for a "destroy" method and it
762        is called. Note that the "Class::Prototyped::destroy" method, which
763        will either be called directly because it shows up in the
764        inheritance hierarchy or will be called indirectly through calls to
765        "$self->reflect->super('destroy');", will delete all non-parent
766        slots from the object. It leaves parent slots alone because the
767        destructors for the parent slots should not be called until such
768        time as the destruction of the object in question is complete
769        (otherwise inherited destructors might still be executing, even
770        though the object to which they belong has already been destroyed).
771        This means that the destructors for objects referenced in non-parent
772        slots may be called, temporarily interrupting the execution sequence
773        in "Class::Prototyped::destroy".
774
775    *   The previously stashed "DESTROY" method is called.
776
777    *   The parent slots for the object are finally removed, thus enabling
778        the destructors for any objects referenced in those parent slots to
779        run.
780
781    *   Final "Class::Prototyped" specific cleanup is run.
782
783"Class::Prototyped::Mirror" Methods
784    These are the methods you can call on the mirror returned from a
785    "reflect" call. If you specify ":EZACCESS" in the "use
786    Class::Prototyped" line, "addSlot", "addSlots", "deleteSlot",
787    "deleteSlots", "getSlot", "getSlots", and "super" will be callable on
788    "Class::Prototyped" objects as well.
789
790  new() - Creates a new "Class::Prototyped::Mirror" object
791    Normally called via the "reflect" method, this can be called directly to
792    avoid using the ":REFLECT" import option for reflecting on non
793    "Class::Prototyped" based classes.
794
795  autoloadCall()
796    If you add an "AUTOLOAD" slot to an object, you will need to get the
797    name of the subroutine being called. "autoloadCall()" returns the name
798    of the subroutine, with the package name stripped off.
799
800  package() - Returns the name of the package for the object
801  object() - Returns the object itself
802  class() - Returns the "class*" slot for the underlying object
803  dump() - Returns a Data::Dumper string representing the object
804  addSlot() - An alias for "addSlots"
805  addSlots() - Add or replace slot definitions
806    Allows you to add or replace slot definitions in the receiver.
807
808        $p->reflect->addSlots(
809            fred        => 'this is fred',
810            doSomething => sub { print 'doing something with ' . $_[1] },
811        );
812        $p->doSomething( $p->fred );
813
814    In addition to the simple form, there is an extended syntax for
815    specifying the slot. In place of the slotname, pass an array reference
816    composed like so:
817
818    "addSlots( [$slotName, $slotType, %slotAttributes] => $slotValue );"
819
820    $slotName is simply the name of the slot, including the trailing "*" if
821    it is a parent slot. $slotType should be 'FIELD', 'METHOD', or 'PARENT'.
822    %slotAttributes should be a list of attribute/value pairs. It is common
823    to use qw() to reduce the amount of typing:
824
825        $p->reflect->addSlot(
826            [qw(bar FIELD)] => "this is a field",
827        );
828
829        $p->reflect->addSlot(
830            [qw(bar FIELD constant 1)] => "this is a constant field",
831        );
832
833        $p->reflect->addSlot(
834            [qw(foo METHOD)] => sub { print "normal method.\n"; },
835        );
836
837        $p->reflect->addSlot(
838            [qw(foo METHOD superable 1)] => sub { print "superable method.\n"; },
839        );
840
841        $p->reflect->addSlot(
842            [qw(parent* PARENT)] => $parent,
843        );
844
845        $p->reflect->addSlot(
846            [qw(parent2* PARENT promote 1)] => $parent2,
847        );
848
849    To make using the extended syntax a bit less cumbersome, however, the
850    following shortcuts are allowed:
851
852    *   $slotType can be omitted. In this case, the slot's type will be
853        determined by inspecting the slot's name (to determine if it is a
854        parent slot) and the slot's value (to determine whether it is a
855        field or method slot). The $slotType value can, however, be used to
856        supply a reference to a code object as the value for a field slot.
857        Note that this means that "FIELD", "METHOD", and "PARENT" are not
858        legal attribute names (since this would make parsing difficult).
859
860    *   If there is only one attribute and if the value is 1, then the value
861        can be omitted.
862
863    Using both of the above contractions, the following are valid short
864    forms for the extended syntax:
865
866        $p->reflect->addSlot(
867            [qw(bar constant)] => "this is a constant field",
868        );
869
870        $p->reflect->addSlot(
871            [qw(foo superable)] => sub { print "superable method.\n"; },
872        );
873
874        $p->reflect->addSlot(
875            [qw(parent2* promote)] => $parent2,
876        );
877
878    The currently defined slot attributes are as follows:
879
880    "FIELD" Slots
881
882        "constant" ("implementor")
883            When true, this defines the field slot as constant, disabling
884            the ability to modify it using the "$object->field($newValue)"
885            syntax. The value may still be modified using the hash syntax
886            (i.e. "$object->{field} = $newValue"). This is mostly useful if
887            you have an object method call that takes parameters, but you
888            wish to replace it on a given object with a hard-coded value by
889            using a field (which makes inspecting the value of the slot
890            through "Data::Dumper" much easier than if you use a "METHOD"
891            slot to return the constant, since code objects are opaque).
892
893        "autoload" ("filter", rank 50)
894            The passed value for the "FIELD" slot should be a subroutine
895            that returns the desired value. Upon the first access, the
896            subroutine will be called, the return value hard-coded into the
897            object by adding the slot (including all otherwise specified
898            attributes), and the value then returned. Useful for
899            implementing constant slots that are costly to initialize,
900            especially those that return lists of "Class::Prototyped"
901            objects!
902
903        "profile" ("filter", rank 80)
904            If "profile" is set to 1, increments
905            "$Class::Prototyped::Mirror::PROFILE::counts->{$package}->{$slot
906            Name}" everytime the slot is accessed. If "profile" is set to 2,
907            increments
908            "$Class::Prototyped::Mirror::PROFILE::counts->{$package}->{$slot
909            Name}->{$caller}" everytime the slot is accessed, where $caller
910            is "$file ($line)".
911
912        "wantarray" ("filter", rank 90)
913            If the field specifies a reference to an array and the call is
914            in list context, dereferences the array and returns a list of
915            values.
916
917        "description" ("advisory")
918            Can be used to specify a description. No real support for this
919            yet beyond that!
920
921    "METHOD" Slots
922
923        "superable" ("filter", rank 10)
924            When true, this enables the "$self->reflect->super( . . . )"
925            calls for this method slot.
926
927        "profile" ("filter", rank 90)
928            See "FIELD" slots for explanation.
929
930        "overload" ("advisory")
931            Set automatically for methods that implement operator
932            overloading.
933
934        "description" ("advisory")
935            See "FIELD" slots for explanation.
936
937    "PARENT" Slots
938
939        "promote" ("advisory")
940            When true, this parent slot is promoted ahead of any other
941            parent slots on the object. This attribute is ephemeral - it is
942            not returned by calls to "getSlot".
943
944        "description" ("advisory")
945            See "FIELD" slots for explanation.
946
947  deleteSlot() - An alias for deleteSlots
948  deleteSlots() - Delete one or more of the receiver's slots by name
949    This will let you delete existing slots in the receiver. If those slots
950    were defined in the receiver's inheritance hierarchy, those inherited
951    definitions will now be available.
952
953        my $p1 = Class::Prototyped->new(
954            field1 => 123,
955            sub1   => sub { print "this is sub1 in p1" },
956            sub2   => sub { print "this is sub2 in p1" }
957        );
958        my $p2 = Class::Prototyped->new(
959            'parent*' => $p1,
960            sub1      => sub { print "this is sub1 in p2" },
961        );
962        $p2->sub1;    # calls $p2.sub1
963        $p2->reflect->deleteSlots('sub1');
964        $p2->sub1;    # calls $p1.sub1
965        $p2->reflect->deleteSlots('sub1');
966        $p2->sub1;    # still calls $p1.sub1
967
968  super() - Call a method defined in a parent
969    The call to a method defined on a parent that is obscured by the current
970    one looks like so:
971
972        $self->reflect->super('method_name', @params);
973
974  slotNames() - Returns a list of all the slot names
975    This is passed an optional type parameter. If specified, it should be
976    one of 'FIELD', 'METHOD', or 'PARENT'. For instance, the following will
977    print out a list of all slots of an object:
978
979      print join(', ', $obj->reflect->slotNames)."\n";
980
981    The following would print out a list of all field slots:
982
983      print join(', ', $obj->reflect->slotNames('FIELD')."\n";
984
985    The parent slot names are returned in the same order for which
986    inheritance is done.
987
988  slotType() - Given a slot name, determines the type
989    This returns 'FIELD', 'METHOD', or 'PARENT'. It croaks if the slot is
990    not defined for that object.
991
992  parents() - Returns a list of all parents
993    Returns a list of all parent object (or package names) for this object.
994
995  allParents() - Returns a list of all parents in the hierarchy
996    Returns a list of all parent objects (or package names) in the object's
997    hierarchy.
998
999  withAllParents() - Same as above, but includes self in the list
1000  allSlotNames() - Returns a list of all slot names
1001defined for the entire inheritance hierarchy
1002    Note that this will return duplicate slot names if inherited slots are
1003    obscured.
1004
1005  getSlot() - Returns the requested slot
1006    When called in scalar context, this returns the thing in the slot. When
1007    called in list context, it returns both the complete form of the
1008    extended syntax for specifying a slot name and the thing in the slot.
1009    There is an optional parameter that can be used to modify the format of
1010    the return value in list context. The allowable values are:
1011
1012    *   'default' - the extended slot syntax and the slot value are returned
1013
1014    *   'simple' - the slot name and the slot value are returned. Note that
1015        in this mode, there is no access to any attributes the slot may have
1016
1017    *   'rotated' - the slot name and the following hash are returned like
1018        so:
1019
1020          $slotName => {
1021            attribs => %slotAttribs,
1022            type => $slotType,
1023            value => $slotValue
1024          },
1025
1026    The latter two options are quite useful when used in conjunction with
1027    the "getSlots" method.
1028
1029  getSlots() - Returns a list of all the slots
1030    This returns a list of extended syntax slot specifiers and their values
1031    ready for sending to "addSlots". It takes first the optional parameter
1032    passed to "slotNames" which specifies the type of slot ('FIELD',
1033    'METHOD', 'PARENT', or "undef") and then the optional parameter passed
1034    to "getSlot", which specifies the format for the return value. If the
1035    latter is 'simple', the returned values can be passed to "addSlots", but
1036    any non-default slot attributes (i.e. "superable" or "constant") will be
1037    lost. If the latter is 'rotated', the returned values are completely
1038    inappropriate for passing to "addSlots". Both 'simple' and 'rotated' are
1039    appropriate for assigning the return values into a hash.
1040
1041    For instance, to add all of the field slots in $bar to $foo:
1042
1043      $foo->reflect->addSlots($bar->reflect->getSlots('FIELD'));
1044
1045    To get a list of all of the slots in the 'simple' format:
1046
1047      my %barSlots = $bar->reflect->getSlots(undef, 'simple');
1048
1049    To get a list of all of the superable method slots in the 'rotated'
1050    format:
1051
1052      my %barMethods = $bar->reflect->getSlots('METHOD', 'rotated');
1053      foreach my $slotName (%barMethods) {
1054        delete $barMethods{$slotName}
1055          unless $barMethods{$slotName}->{attribs}->{superable};
1056      }
1057
1058  promoteParents() - This changes the ordering of the parent slots
1059    This expects a list of parent slot names. There should be no duplicates
1060    and all of the parent slot names should be already existing parent slots
1061    on the object. These parent slots will be moved forward in the hierarchy
1062    in the order that they are passed. Unspecified parent slots will retain
1063    their current positions relative to other unspecified parent slots, but
1064    as a group they will be moved to the end of the hierarchy.
1065
1066  tiedInterfacePackage() - This specifies the tied interface package
1067    This allows you to specify the sort of tied interface you wish to offer
1068    when code accesses the object as a hash reference. If no parameter is
1069    passed, this will return the current tied interface package active for
1070    the object. If a parameter is passed, it should specify either the
1071    package name or an alias. The currently known aliases are:
1072
1073    default
1074        This specifies "Class::Prototyped::Tied::Default" as the tie class.
1075        The default behavior is to allow access to existing fields, but
1076        attempts to create fields, access methods, or delete slots will
1077        croak. This is the tie class used by "Class::Prototyped" (unless you
1078        do something very naughty and call
1079        "Class::Prototyped->reflect->tiedInterfacePackage($not_default)"),
1080        and as such is the fallback behavior for classes and objects if they
1081        don't get a different value from their inheritance.
1082
1083    autovivify
1084        This specifies "Class::Prototyped::Tied::AutoVivify" as the tie
1085        class. The behavior of this package allows access to existing
1086        fields, will automatically create field slots if they don't exist,
1087        and will allow deletion of field slots. Attempts to access or delete
1088        method or parent slots will croak.
1089
1090    Calls to "new" and "clone" will use the tied interface in use on the
1091    existing object/package. When "reflect" is called for the first time on
1092    a class package, it will use the tied interface of its first parent
1093    class (i.e. $ISA[0]). If that package has not yet had "reflect" called
1094    on it, it will check its parent, and so on and so forth. If none of the
1095    packages in the primary inheritance fork have been reflected upon, the
1096    value for "Class::Prototyped" will be used, which should be "default".
1097
1098  defaultAttributes() - get and set default attributes
1099    This isn't particularly pretty. The general syntax looks something like:
1100
1101        my $temp = MyClass->reflect->defaultAttributes;
1102        $temp->{METHOD}->{superable} = 1;
1103        MyClass->reflect->defaultAttributes($temp);
1104
1105    The return value from "defaultAttributes" is a hash with the keys
1106    'FIELD', 'METHOD', and 'PARENT'. The values are either "undef" or hash
1107    references consisting of the attributes and their default values. Modify
1108    the data structure as desired and pass it back to "defaultAttributes" to
1109    change the default attributes for that object or class. Note that
1110    default attributes are not inherited dynamically - the inheritance
1111    occurs when a new object is created, but from that point on changes to a
1112    parent object are not inherited by the child. Global changes can be
1113    effected by modifying the "defaultAttributes" for "Class::Prototyped" in
1114    a sufficiently early "BEGIN" block. Note that making global changes like
1115    this is "not" recommended for production modules as it may interfere
1116    with other modules that rely upon "Class::Prototyped".
1117
1118  wrap()
1119  unwrap()
1120  delegate()
1121    delegate name => slot name can be string, regex, or array of same. slot
1122    can be slot name, or object, or 2-element array with slot name or object
1123    and method name. You can delegate to a parent.
1124
1125  include() - include a package or external file
1126    You can "require" an arbitrary file in the namespace of an object or
1127    class without adding to the parents using "include()" :
1128
1129      $foo->include( 'xx.pl' );
1130
1131    will include whatever is in xx.pl. Likewise for modules:
1132
1133      $foo->include( 'MyModule' );
1134
1135    will search along your @INC path for "MyModule.pm" and include it.
1136
1137    You can specify a second parameter that will be the name of a subroutine
1138    that you can use in your included code to refer to the object into which
1139    the code is being included (as long as you don't change packages in the
1140    included code). The subroutine will be removed after the include, so
1141    don't call it from any subroutines defined in the included code.
1142
1143    If you have the following in "File.pl":
1144
1145        sub b {'xxx.b'}
1146
1147        sub c { return thisObject(); }    # DON'T DO THIS!
1148
1149        thisObject()->reflect->addSlots(
1150            'parent*' => 'A',
1151            d         => 'added.d',
1152            e         => sub {'xxx.e'},
1153        );
1154
1155    And you include it using:
1156
1157        $mirror->include('File.pl', 'thisObject');
1158
1159    Then the "addSlots" will work fine, but if sub "c" is called, it won't
1160    find "thisObject()".
1161
1162AUTHOR
1163    Written by Ned Konz, perl@bike-nomad.com and Toby Ovod-Everett,
1164    toby@ovod-everett.org. 5.005_03 porting by chromatic.
1165
1166    Toby Ovod-Everett is currently maintaining the package.
1167
1168LICENSE
1169    Copyright 2001-2004 Ned Konz and Toby Ovod-Everett. All rights reserved.
1170    This program is free software; you can redistribute it and/or modify it
1171    under the same terms as Perl itself.
1172
1173SEE ALSO
1174    Class::SelfMethods
1175
1176    Class::Object
1177
1178    Class::Classless
1179
1180