1Object::InsideOut(3)  User Contributed Perl Documentation Object::InsideOut(3)
2
3
4

NAME

6       Object::InsideOut - Comprehensive inside-out object support module
7

VERSION

9       This document describes Object::InsideOut version 3.56
10

SYNOPSIS

12        package My::Class; {
13            use Object::InsideOut;
14
15            # Numeric field
16            #   With combined get+set accessor
17            my @data
18                   :Field
19                   :Type(numeric)
20                   :Accessor(data);
21
22            # Takes 'INPUT' (or 'input', etc.) as a mandatory parameter to ->new()
23            my %init_args :InitArgs = (
24                'INPUT' => {
25                    'Regex'     => qr/^input$/i,
26                    'Mandatory' => 1,
27                    'Type'      => 'numeric',
28                },
29            );
30
31            # Handle class-specific args as part of ->new()
32            sub init :Init
33            {
34                my ($self, $args) = @_;
35
36                # Put 'input' parameter into 'data' field
37                $self->set(\@data, $args->{'INPUT'});
38            }
39        }
40
41        package My::Class::Sub; {
42            use Object::InsideOut qw(My::Class);
43
44            # List field
45            #   With standard 'get_X' and 'set_X' accessors
46            #   Takes 'INFO' as an optional list parameter to ->new()
47            #     Value automatically added to @info array
48            #     Defaults to [ 'empty' ]
49            my @info
50                   :Field
51                   :Type(list)
52                   :Standard(info)
53                   :Arg('Name' => 'INFO', 'Default' => 'empty');
54        }
55
56        package Foo; {
57            use Object::InsideOut;
58
59            # Field containing My::Class objects
60            #   With combined accessor
61            #   Plus automatic parameter processing on object creation
62            my @foo
63                   :Field
64                   :Type(My::Class)
65                   :All(foo);
66        }
67
68        package main;
69
70        my $obj = My::Class::Sub->new('Input' => 69);
71        my $info = $obj->get_info();               # [ 'empty' ]
72        my $data = $obj->data();                   # 69
73        $obj->data(42);
74        $data = $obj->data();                      # 42
75
76        $obj = My::Class::Sub->new('INFO' => 'help', 'INPUT' => 86);
77        $data = $obj->data();                      # 86
78        $info = $obj->get_info();                  # [ 'help' ]
79        $obj->set_info(qw(foo bar baz));
80        $info = $obj->get_info();                  # [ 'foo', 'bar', 'baz' ]
81
82        my $foo_obj = Foo->new('foo' => $obj);
83        $foo_obj->foo()->data();                   # 86
84

DESCRIPTION

86       This module provides comprehensive support for implementing classes
87       using the inside-out object model.
88
89       Object::InsideOut implements inside-out objects as anonymous scalar
90       references that are blessed into a class with the scalar containing the
91       ID for the object (usually a sequence number).  For Perl 5.8.3 and
92       later, the scalar reference is set as read-only to prevent accidental
93       modifications to the ID.  Object data (i.e., fields) are stored within
94       the class's package in either arrays indexed by the object's ID, or
95       hashes keyed to the object's ID.
96
97       The virtues of the inside-out object model over the blessed hash object
98       model have been extolled in detail elsewhere.  See the informational
99       links under "SEE ALSO".  Briefly, inside-out objects offer the
100       following advantages over blessed hash objects:
101
102       ·   Encapsulation
103
104           Object data is enclosed within the class's code and is accessible
105           only through the class-defined interface.
106
107       ·   Field Name Collision Avoidance
108
109           Inheritance using blessed hash classes can lead to conflicts if any
110           classes use the same name for a field (i.e., hash key).  Inside-out
111           objects are immune to this problem because object data is stored
112           inside each class's package, and not in the object itself.
113
114       ·   Compile-time Name Checking
115
116           A common error with blessed hash classes is the misspelling of
117           field names:
118
119            $obj->{'coment'} = 'Say what?';   # Should be 'comment' not 'coment'
120
121           As there is no compile-time checking on hash keys, such errors do
122           not usually manifest themselves until runtime.
123
124           With inside-out objects, text hash keys are not used for accessing
125           field data.  Field names and the data index (i.e., $$self) are
126           checked by the Perl compiler such that any typos are easily caught
127           using "perl -c".
128
129            $coment[$$self] = $value;    # Causes a compile-time error
130               # or with hash-based fields
131            $comment{$$self} = $value;   # Also causes a compile-time error
132
133       Object::InsideOut offers all the capabilities of other inside-out
134       object modules with the following additional key advantages:
135
136       ·   Speed
137
138           When using arrays to store object data, Object::InsideOut objects
139           are as much as 40% faster than blessed hash objects for fetching
140           and setting data, and even with hashes they are still several
141           percent faster than blessed hash objects.
142
143       ·   Threads
144
145           Object::InsideOut is thread safe, and thoroughly supports sharing
146           objects between threads using threads::shared.
147
148       ·   Flexibility
149
150           Allows control over object ID specification, accessor naming,
151           parameter name matching, and much more.
152
153       ·   Runtime Support
154
155           Supports classes that may be loaded at runtime (i.e., using
156           "eval { require ...; };").  This makes it usable from within
157           mod_perl, as well.  Also supports additions to class hierarchies,
158           and dynamic creation of object fields during runtime.
159
160       ·   Perl 5.6 and 5.8
161
162           Tested on Perl v5.6.0 through v5.6.2, v5.8.0 through v5.8.8, and
163           v5.9.4.
164
165       ·   Exception Objects
166
167           Object::InsideOut uses Exception::Class for handling errors in an
168           OO-compatible manner.
169
170       ·   Object Serialization
171
172           Object::InsideOut has built-in support for object dumping and
173           reloading that can be accomplished in either an automated fashion
174           or through the use of class-supplied subroutines.  Serialization
175           using Storable is also supported.
176
177       ·   Foreign Class Inheritance
178
179           Object::InsideOut allows classes to inherit from foreign (i.e.,
180           non-Object::InsideOut) classes, thus allowing you to sub-class
181           other Perl class, and access their methods from your own objects.
182
183       ·   Introspection
184
185           Obtain constructor parameters and method metadata for
186           Object::InsideOut classes.
187

CLASSES

189       To use this module, each of your classes will start with
190       "use Object::InsideOut;":
191
192        package My::Class; {
193            use Object::InsideOut;
194            ...
195        }
196
197       Sub-classes (child classes) inherit from base classes (parent classes)
198       by telling Object::InsideOut what the parent class is:
199
200        package My::Sub; {
201            use Object::InsideOut qw(My::Parent);
202            ...
203        }
204
205       Multiple inheritance is also supported:
206
207        package My::Project; {
208            use Object::InsideOut qw(My::Class Another::Class);
209            ...
210        }
211
212       Object::InsideOut acts as a replacement for the "base" pragma:  It
213       loads the parent module(s), calls their "->import()" methods, and sets
214       up the sub-class's @ISA array.  Therefore, you should not
215       "use base ..." yourself, nor try to set up @ISA arrays.  Further, you
216       should not use a class's @ISA array to determine a class's hierarchy:
217       See "INTROSPECTION" for details on how to do this.
218
219       If a parent class takes parameters (e.g., symbols to be exported via
220       Exporter), enclose them in an array ref (mandatory) following the name
221       of the parent class:
222
223        package My::Project; {
224            use Object::InsideOut 'My::Class'      => [ 'param1', 'param2' ],
225                                  'Another::Class' => [ 'param' ];
226            ...
227        }
228

OBJECTS

230   Object Creation
231       Objects are created using the "->new()" method which is exported by
232       Object::InsideOut to each class, and is invoked in the following
233       manner:
234
235        my $obj = My::Class->new();
236
237       Object::InsideOut then handles all the messy details of initializing
238       the object in each of the classes in the invoking class's hierarchy.
239       As such, classes do not (normally) implement their own "->new()"
240       method.
241
242       Usually, object fields are initially populated with data as part of the
243       object creation process by passing parameters to the "->new()" method.
244       Parameters are passed in as combinations of "key => value" pairs and/or
245       hash refs:
246
247        my $obj = My::Class->new('param1' => 'value1');
248            # or
249        my $obj = My::Class->new({'param1' => 'value1'});
250            # or even
251        my $obj = My::Class->new(
252            'param_X' => 'value_X',
253            'param_Y' => 'value_Y',
254            {
255                'param_A' => 'value_A',
256                'param_B' => 'value_B',
257            },
258            {
259                'param_Q' => 'value_Q',
260            },
261        );
262
263       Additionally, parameters can be segregated in hash refs for specific
264       classes:
265
266        my $obj = My::Class->new(
267            'foo' => 'bar',
268            'My::Class'      => { 'param' => 'value' },
269            'Parent::Class'  => { 'data'  => 'info'  },
270        );
271
272       The initialization methods for both classes in the above will get
273       'foo' => 'bar', "My::Class" will also get 'param' => 'value', and
274       "Parent::Class" will also get 'data' => 'info'.  In this scheme, class-
275       specific parameters will override general parameters specified at a
276       higher level:
277
278        my $obj = My::Class->new(
279            'default' => 'bar',
280            'Parent::Class'  => { 'default' => 'baz' },
281        );
282
283       "My::Class" will get 'default' => 'bar', and "Parent::Class" will get
284       'default' => 'baz'.
285
286       Calling "->new()" on an object works, too, and operates the same as
287       calling "->new()" for the class of the object (i.e., "$obj->new()" is
288       the same as "ref($obj)->new()").
289
290       How the parameters passed to the "->new()" method are used to
291       initialize the object is discussed later under "OBJECT INITIALIZATION".
292
293       NOTE: You cannot create objects from Object::InsideOut itself:
294
295        # This is an error
296        # my $obj = Object::InsideOut->new();
297
298       In this way, Object::InsideOut is not an object class, but functions
299       more like a pragma.
300
301   Object IDs
302       As stated earlier, this module implements inside-out objects as
303       anonymous, read-only scalar references that are blessed into a class
304       with the scalar containing the ID for the object.
305
306       Within methods, the object is passed in as the first argument:
307
308        sub my_method
309        {
310            my $self = shift;
311            ...
312        }
313
314       The object's ID is then obtained by dereferencing the object:  $$self.
315       Normally, this is only needed when accessing the object's field data:
316
317        my @my_field :Field;
318
319        sub my_method
320        {
321            my $self = shift;
322            ...
323            my $data = $my_field[$$self];
324            ...
325        }
326
327       At all other times, and especially in application code, the object
328       should be treated as an opaque entity.
329

ATTRIBUTES

331       Much of the power of Object::InsideOut comes from the use of
332       attributes: Tags on variables and subroutines that the attributes
333       module sends to Object::InsideOut at compile time.  Object::InsideOut
334       then makes use of the information in these tags to handle such
335       operations as object construction, automatic accessor generation, and
336       so on.
337
338       (Note:  The use of attributes is not the same thing as source
339       filtering.)
340
341       An attribute consists of an identifier preceded by a colon, and
342       optionally followed by a set of parameters in parentheses.  For
343       example, the attributes on the following array declare it as an object
344       field, and specify the generation of an accessor method for that field:
345
346        my @level :Field :Accessor(level);
347
348       When multiple attributes are assigned to a single entity, they may all
349       appear on the same line (as shown above), or on separate lines:
350
351        my @level
352            :Field
353            :Accessor(level);
354
355       However, due to limitations in the Perl parser, the entirety of any one
356       attribute must be on a single line:
357
358        # This doesn't work
359        # my @level
360        #     :Field
361        #     :Accessor('Name'   => 'level',
362        #               'Return' => 'Old');
363
364        # Each attribute must be all on one line
365        my @level
366            :Field
367            :Accessor('Name' => 'level', 'Return' => 'Old');
368
369       For Object::InsideOut's purposes, the case of an attribute's name does
370       not matter:
371
372        my @data :Field;
373           # or
374        my @data :FIELD;
375
376       However, by convention (as denoted in the attributes module), an
377       attribute's name should not be all lowercase.
378

FIELDS

380   Field Declarations
381       Object data fields consist of arrays within a class's package into
382       which data are stored using the object's ID as the array index.  An
383       array is declared as being an object field by following its declaration
384       with the ":Field" attribute:
385
386        my @info :Field;
387
388       Object data fields may also be hashes:
389
390        my %data :Field;
391
392       However, as array access is as much as 40% faster than hash access, you
393       should stick to using arrays.  See "HASH ONLY CLASSES" for more
394       information on when hashes may be required.
395
396   Getting Data
397       In class code, data can be fetched directly from an object's field
398       array (hash) using the object's ID:
399
400        $data = $field[$$self];
401            # or
402        $data = $field{$$self};
403
404   Setting Data
405       Analogous to the above, data can be put directly into an object's field
406       array (hash) using the object's ID:
407
408        $field[$$self] = $data;
409            # or
410        $field{$$self} = $data;
411
412       However, in threaded applications that use data sharing (i.e., use
413       "threads::shared"), the above will not work when the object is shared
414       between threads and the data being stored is either an array, hash or
415       scalar reference (this includes other objects).  This is because the
416       $data must first be converted into shared data before it can be put
417       into the field.
418
419       Therefore, Object::InsideOut automatically exports a method called
420       "->set()" to each class.  This method should be used in class code to
421       put data into object fields whenever there is the possibility that the
422       class code may be used in an application that uses threads::shared
423       (i.e., to make your class code thread-safe).  The "->set()" method
424       handles all details of converting the data to a shared form, and
425       storing it in the field.
426
427       The "->set()" method, requires two arguments:  A reference to the
428       object field array/hash, and the data (as a scalar) to be put in it:
429
430        my @my_field :Field;
431
432        sub store_data
433        {
434            my ($self, $data) = @_;
435            ...
436            $self->set(\@my_field, $data);
437        }
438
439       To be clear, the "->set()" method is used inside class code; not
440       application code.  Use it inside any object methods that set data in
441       object field arrays/hashes.
442
443       In the event of a method naming conflict, the "->set()" method can be
444       called using its fully-qualified name:
445
446        $self->Object::InsideOut::set(\@field, $data);
447

OBJECT INITIALIZATION

449       As stated in "Object Creation", object fields are initially populated
450       with data as part of the object creation process by passing
451       "key => value" parameters to the "->new()" method.  These parameters
452       can be processed automatically into object fields, or can be passed to
453       a class-specific object initialization subroutine.
454
455   Field-Specific Parameters
456       When an object creation parameter corresponds directly to an object
457       field, you can specify for Object::InsideOut to automatically place the
458       parameter into the field by adding the ":Arg" attribute to the field
459       declaration:
460
461        my @foo :Field :Arg(foo);
462
463       For the above, the following would result in $val being placed in
464       "My::Class"'s @foo field during object creation:
465
466        my $obj = My::Class->new('foo' => $val);
467
468   Object Initialization Subroutines
469       Many times, object initialization parameters do not correspond directly
470       to object fields, or they may require special handling.  For these,
471       parameter processing is accomplished through a combination of an
472       ":InitArgs" labeled hash, and an ":Init" labeled subroutine.
473
474       The ":InitArgs" labeled hash specifies the parameters to be extracted
475       from the argument list supplied to the "->new()" method.  Those
476       parameters (and only those parameters) which match the keys in the
477       ":InitArgs" hash are then packaged together into a single hash ref.
478       The newly created object and this parameter hash ref are then sent to
479       the ":Init" subroutine for processing.
480
481       Here is an example of a class with an automatically handled field and
482       an :Init handled field:
483
484        package My::Class; {
485            use Object::InsideOut;
486
487            # Automatically handled field
488            my @my_data  :Field  :Acc(data)  :Arg(MY_DATA);
489
490            # ':Init' handled field
491            my @my_field :Field;
492
493            my %init_args :InitArgs = (
494                'MY_PARAM' => '',
495            );
496
497            sub _init :Init
498            {
499                my ($self, $args) = @_;
500
501                if (exists($args->{'MY_PARAM'})) {
502                    $self->set(\@my_field, $args->{'MY_PARAM'});
503                }
504            }
505
506            ...
507        }
508
509       An object for this class would be created as follows:
510
511        my $obj = My::Class->new('MY_DATA'  => $dat,
512                                 'MY_PARAM' => $parm);
513
514       This results in, first of all, $dat being placed in the object's
515       @my_data field because the "MY_DATA" key is specified in the ":Arg"
516       attribute for that field.
517
518       Then, "_init" is invoked with arguments consisting of the object (i.e.,
519       $self) and a hash ref consisting only of "{ 'MY_PARAM' => $param }"
520       because the key "MY_PARAM" is specified in the ":InitArgs" hash.
521       "_init" checks that the parameter "MY_PARAM" exists in the hash ref,
522       and then (since it does exist) adds $parm to the object's @my_field
523       field.
524
525       Setting Data
526           Data processed by the ":Init" subroutine may be placed directly
527           into the class's field arrays (hashes) using the object's ID (i.e.,
528           $$self):
529
530            $my_field[$$self] = $args->{'MY_PARAM'};
531
532           However, as shown in the example above, it is strongly recommended
533           that you use the ->set() method:
534
535            $self->set(\@my_field, $args->{'MY_PARAM'});
536
537           which handles converting the data to a shared format when needed
538           for applications using threads::shared.
539
540       All Parameters
541           The ":InitArgs" hash and the ":Arg" attribute on fields act as
542           filters that constrain which initialization parameters are and are
543           not sent to the ":Init" subroutine.  If, however, a class does not
544           have an ":InitArgs" hash and does not use the ":Arg" attribute on
545           any of its fields, then its ":Init" subroutine (if it exists, of
546           course) will get all the initialization parameters supplied to the
547           "->new()" method.
548
549   Mandatory Parameters
550       Field-specific parameters may be declared mandatory as follows:
551
552        my @data :Field
553                 :Arg('Name' => 'data', 'Mandatory' => 1);
554
555       If a mandatory parameter is missing from the argument list to
556       "->new()", an error is generated.
557
558       For ":Init" handled parameters, use:
559
560        my %init_args :InitArgs = (
561            'data' => {
562                'Mandatory' => 1,
563            },
564        );
565
566       "Mandatory" may be abbreviated to "Mand", and "Required" or "Req" are
567       synonymous.
568
569   Default Values
570       For optional parameters, defaults can be specified for field-specific
571       parameters:
572
573        my @data :Field
574                 :Arg('Name' => 'data', 'Default' => 'foo');
575
576       If an optional parameter with a specified default is missing from the
577       argument list to "->new()", then the default is assigned to the field
578       when the object is created (before the ":Init" subroutine, if any, is
579       called).
580
581       The format for ":Init" handled parameters is:
582
583        my %init_args :InitArgs = (
584            'data' => {
585                'Default' => 'foo',
586            },
587        );
588
589       In this case, if the parameter is missing from the argument list to
590       "->new()", then the parameter key is paired with the default value and
591       added to the ":Init" argument hash ref (e.g., "{ 'data' => 'foo' }").
592
593       "Default" may be abbreviated to "Def".
594
595       Fields can also be assigned a default value even if not associated with
596       an initialization parameter:
597
598        my @data :Field
599                 :Default('foo');
600
601       Note that when using ":Default", the value must be properly specified
602       (e.g., strings must be quoted as illustrated above).
603
604       Using an array or hash reference as a default will probably not produce
605       the result that you might expect:
606
607        my @foo :Field
608                :Default({});
609
610       This does not result in a new empty hash reference being created for
611       each new object.  Rather, a single empty hash reference is created when
612       the module is loaded, and then that reference is assigned to each newly
613       created object.  In other words, it is equivalent to:
614
615        my %bar = ();
616
617        my @foo :Field
618                :Default(\%bar);
619
620       To get the other result, assign a new empty hash reference using an
621       ":Init" subroutine:
622
623        sub _init :Init
624        {
625            my ($self, $args) = @_;
626
627            if (! exists($foo[$$self])) {
628                $self->set(\@foo, {});
629            }
630        }
631
632       ":Default" may be abbreviated to ":Def".
633
634   Parameter Name Matching
635       Rather than having to rely on exact matches to parameter keys in the
636       "->new()" argument list, you can specify a regular expressions to be
637       used to match them to field-specific parameters:
638
639        my @param :Field
640                  :Arg('Name' => 'param', 'Regexp' => qr/^PARA?M$/i);
641
642       In this case, the parameter's key could be any of the following: PARAM,
643       PARM, Param, Parm, param, parm, and so on.  And the following would
644       result in $data being placed in "My::Class"'s @param field during
645       object creation:
646
647        my $obj = My::Class->new('Parm' => $data);
648
649       For ":Init" handled parameters, you would similarly use:
650
651        my %init_args :InitArgs = (
652            'Param' => {
653                'Regex' => qr/^PARA?M$/i,
654            },
655        );
656
657       In this case, the match results in "{ 'Param' => $data }" being sent to
658       the ":Init" subroutine as the argument hash.  Note that the ":InitArgs"
659       hash key is substituted for the original argument key.  This eliminates
660       the need for any parameter key pattern matching within the ":Init"
661       subroutine.
662
663       "Regexp" may be abbreviated to "Regex" or "Re".
664
665   Object Pre-initialization
666       Occasionally, a child class may need to send a parameter to a parent
667       class as part of object initialization.  This can be accomplished by
668       supplying a ":PreInit" labeled subroutine in the child class.  These
669       subroutines, if found, are called in order from the bottom of the class
670       hierarchy upward (i.e., child classes first).
671
672       The subroutine should expect two arguments:  The newly created
673       (uninitialized) object (i.e., $self), and a hash ref of all the
674       parameters from the "->new()" method call, including any additional
675       parameters added by other ":PreInit" subroutines.
676
677        sub pre_init :PreInit
678        {
679            my ($self, $args) = @_;
680            ...
681        }
682
683       The parameter hash ref will not be exactly as supplied to "->new()",
684       but will be flattened into a single hash ref.  For example,
685
686        my $obj = My::Class->new(
687            'param_X' => 'value_X',
688            {
689                'param_A' => 'value_A',
690                'param_B' => 'value_B',
691            },
692            'My::Class' => { 'param' => 'value' },
693        );
694
695       would produce
696
697        {
698            'param_X' => 'value_X',
699            'param_A' => 'value_A',
700            'param_B' => 'value_B',
701            'My::Class' => { 'param' => 'value' }
702        }
703
704       as the hash ref to the ":PreInit" subroutine.
705
706       The ":PreInit" subroutine may then add, modify or even remove any
707       parameters from the hash ref as needed for its purposes.  After all the
708       ":PreInit" subroutines have been executed, object initialization will
709       then proceed using the resulting parameter hash.
710
711       The ":PreInit" subroutine should not try to set data in its class's
712       fields or in other class's fields (e.g., using set methods) as such
713       changes will be overwritten during initialization phase which follows
714       pre-initialization.  The ":PreInit" subroutine is only intended for
715       modifying initialization parameters prior to initialization.
716
717   Initialization Sequence
718       For the most part, object initialization can be conceptualized as
719       proceeding from parent classes down through child classes.  As such,
720       calling child class methods from a parent class during object
721       initialization may not work because the object will not have been fully
722       initialized in the child classes.
723
724       Knowing the order of events during object initialization may help in
725       determining when this can be done safely:
726
727       1.  The scalar reference for the object is created, populated with an
728       "Object ID", and blessed into the appropriate class.
729       2.  :PreInit subroutines are called in order from the bottom of the
730       class hierarchy upward (i.e., child classes first).
731       3.  From the top of the class hierarchy downward (i.e., parent classes
732       first), "Default Values" are assigned to fields.  (These may be
733       overwritten by subsequent steps below.)
734       4.  From the top of the class hierarchy downward, parameters to the
735       "->new()" method are processed for ":Arg" field attributes and entries
736       in the ":InitArgs" hash:
737           a.  "Parameter Preprocessing" is performed.
738           b.  Checks for "Mandatory Parameters" are made.
739           c.  "Default Values" specified in the ":InitArgs" hash are added
740           for subsequent processing by the ":Init" subroutine.
741           d.  Type checking is performed.
742           e.  "Field-Specific Parameters" are assigned to fields.
743       5.  From the top of the class hierarchy downward, :Init subroutines are
744       called with parameters specified in the ":InitArgs" hash.
745       6.  Checks are made for any parameters to "->new()" that were not
746       handled in the above.  (See next section.)
747
748   Unhandled Parameters
749       It is an error to include any parameters to the "->new()" method that
750       are not handled by at least one class in the hierarchy.  The primary
751       purpose of this is to catch typos in parameter names:
752
753         my $obj = Person->new('nane' => 'John');   # Should be 'name'
754
755       The only time that checks for unhandled parameters are not made is when
756       at least one class in the hierarchy does not have an ":InitArgs" hash
757       and does not use the ":Arg" attribute on any of its fields and uses an
758       :Init subroutine for processing parameters.  In such a case, it is not
759       possible for Object::InsideOut to determine which if any of the
760       parameters are not handled by the ":Init" subroutine.
761
762   Modifying ":InitArgs"
763       For performance purposes, Object::InsideOut normalizes each class's
764       ":InitArgs" hash by creating keys in the form of '_X' for the various
765       options it handles (e.g., '_R' for 'Regexp').
766
767       If a class has the unusual requirement to modify its ":InitArgs" hash
768       during runtime, then it must renormalize the hash after making such
769       changes by invoking "Object::InsideOut::normalize()" on it so that
770       Object::InsideOut will pick up the changes:
771
772        Object::InsideOut::normalize(\%init_args);
773

ACCESSOR GENERATION

775       Accessors are object methods used to get data out of and put data into
776       an object.  You can, of course, write your own accessor code, but this
777       can get a bit tedious, especially if your class has lots of fields.
778       Object::InsideOut provides the capability to automatically generate
779       accessors for you.
780
781   Basic Accessors
782       A get accessor is vary basic:  It just returns the value of an object's
783       field:
784
785        my @data :Field;
786
787        sub fetch_data
788        {
789            my $self = shift;
790            return ($data[$$self]);
791        }
792
793       and you would use it as follows:
794
795        my $data = $obj->fetch_data();
796
797       To have Object::InsideOut generate such a get accessor for you, add a
798       ":Get" attribute to the field declaration, specifying the name for the
799       accessor in parentheses:
800
801        my @data :Field :Get(fetch_data);
802
803       Similarly, a set accessor puts data in an object's field.  The set
804       accessors generated by Object::InsideOut check that they are called
805       with at least one argument.  They are specified using the ":Set"
806       attribute:
807
808        my @data :Field :Set(store_data);
809
810       Some programmers use the convention of naming get and set accessors
811       using get_ and set_ prefixes.  Such standard accessors can be generated
812       using the ":Standard" attribute (which may be abbreviated to ":Std"):
813
814        my @data :Field :Std(data);
815
816       which is equivalent to:
817
818        my @data :Field :Get(get_data) :Set(set_data);
819
820       Other programmers prefer to use a single combination accessors that
821       performs both functions:  When called with no arguments, it gets, and
822       when called with an argument, it sets.  Object::InsideOut will generate
823       such accessors with the ":Accessor" attribute.  (This can be
824       abbreviated to ":Acc", or you can use ":Get_Set" or ":Combined" or
825       ":Combo" or even "Mutator".)  For example:
826
827        my @data :Field :Acc(data);
828
829       The generated accessor would be used in this manner:
830
831        $obj->data($val);           # Puts data into the object's field
832        my $data = $obj->data();    # Fetches the object's field data
833
834   Set Accessor Return Value
835       For any of the automatically generated methods that perform set
836       operations, the default for the method's return value is the value
837       being set (i.e., the new value).
838
839       You can specify the set accessor's return value using the "Return"
840       attribute parameter (which may be abbreviated to "Ret").  For example,
841       to explicitly specify the default behavior use:
842
843        my @data :Field :Set('Name' => 'store_data', 'Return' => 'New');
844
845       You can specify that the accessor should return the old (previous)
846       value (or "undef" if unset):
847
848        my @data :Field :Acc('Name' => 'data', 'Ret' => 'Old');
849
850       You may use "Previous", "Prev" or "Prior" as synonyms for "Old".
851
852       Finally, you can specify that the accessor should return the object
853       itself:
854
855        my @data :Field :Std('Name' => 'data', 'Ret' => 'Object');
856
857       "Object" may be abbreviated to "Obj", and is also synonymous with
858       "Self".
859
860   Method Chaining
861       An obvious case where method chaining can be used is when a field is
862       used to store an object:  A method for the stored object can be chained
863       to the get accessor call that retrieves that object:
864
865        $obj->get_stored_object()->stored_object_method()
866
867       Chaining can be done off of set accessors based on their return value
868       (see above).  In this example with a set accessor that returns the new
869       value:
870
871        $obj->set_stored_object($stored_obj)->stored_object_method()
872
873       the set_stored_object() call stores the new object, returning it as
874       well, and then the stored_object_method() call is invoked via the
875       stored/returned object.  The same would work for set accessors that
876       return the old value, too, but in that case the chained method is
877       invoked via the previously stored (and now returned) object.
878
879       If the Want module (version 0.12 or later) is available, then
880       Object::InsideOut also tries to do the right thing with method chaining
881       for set accessors that don't store/return objects.  In this case, the
882       object used to invoke the set accessor will also be used to invoke the
883       chained method (just as though the set accessor were declared with
884       'Return' => 'Object'):
885
886        $obj->set_data('data')->do_something();
887
888       To make use of this feature, just add "use Want;" to the beginning of
889       your application.
890
891       Note, however, that this special handling does not apply to get
892       accessors, nor to combination accessors invoked without an argument
893       (i.e., when used as a get accessor).  These must return objects in
894       order for method chaining to succeed.
895
896   :lvalue Accessors
897       As documented in "Lvalue subroutines" in perlsub, an ":lvalue"
898       subroutine returns a modifiable value.  This modifiable value can then,
899       for example, be used on the left-hand side (hence "LVALUE") of an
900       assignment statement, or a substitution regular expression.
901
902       For Perl 5.8.0 and later, Object::InsideOut supports the generation of
903       ":lvalue" accessors such that their use in an "LVALUE" context will set
904       the value of the object's field.  Just add "'lvalue' => 1" to the set
905       accessor's attribute.  ('lvalue' may be abbreviated to 'lv'.)
906
907       Additionally, ":Lvalue" (or its abbreviation ":lv") may be used for a
908       combined get/set :lvalue accessor.  In other words, the following are
909       equivalent:
910
911        :Acc('Name' => 'email', 'lvalue' => 1)
912
913        :Lvalue(email)
914
915       Here is a detailed example:
916
917        package Contact; {
918            use Object::InsideOut;
919
920            # Create separate a get accessor and an :lvalue set accessor
921            my @name  :Field
922                      :Get(name)
923                      :Set('Name' => 'set_name', 'lvalue' => 1);
924
925            # Create a standard get_/set_ pair of accessors
926            #   The set_ accessor will be an :lvalue accessor
927            my @phone :Field
928                      :Std('Name' => 'phone', 'lvalue' => 1);
929
930            # Create a combined get/set :lvalue accessor
931            my @email :Field
932                      :Lvalue(email);
933        }
934
935        package main;
936
937        my $obj = Contact->new();
938
939        # Use :lvalue accessors in assignment statements
940        $obj->set_name()  = 'Jerry D. Hedden';
941        $obj->set_phone() = '800-555-1212';
942        $obj->email()     = 'jdhedden AT cpan DOT org';
943
944        # Use :lvalue accessor in substituion regexp
945        $obj->email() =~ s/ AT (\w+) DOT /\@$1./;
946
947        # Use :lvalue accessor in a 'substr' call
948        substr($obj->set_phone(), 0, 3) = '888';
949
950        print("Contact info:\n");
951        print("\tName:  ", $obj->name(),      "\n");
952        print("\tPhone: ", $obj->get_phone(), "\n");
953        print("\tEmail: ", $obj->email(),     "\n");
954
955       The use of ":lvalue" accessors requires the installation of the Want
956       module (version 0.12 or later) from CPAN.  See particularly the section
957       "Lvalue subroutines:" in Want for more information.
958
959       ":lvalue" accessors also work like regular set accessors in being able
960       to accept arguments, return values, and so on:
961
962        my @pri :Field
963                :Lvalue('Name' => 'priority', 'Return' => 'Old');
964         ...
965        my $old_pri = $obj->priority(10);
966
967       ":lvalue" accessors can be used in method chains.
968
969       Caveats: While still classified as experimental, Perl's support for
970       ":lvalue" subroutines has been around since 5.6.0, and a good number of
971       CPAN modules make use of them.
972
973       By definition, because ":lvalue" accessors return the location of a
974       field, they break encapsulation.  As a result, some OO advocates eschew
975       the use of ":lvalue" accessors.
976
977       ":lvalue" accessors are slower than corresponding non-lvalue accessors.
978       This is due to the fact that more code is needed to handle all the
979       diverse ways in which ":lvalue" accessors may be used.  (I've done my
980       best to optimize the generated code.)  For example, here's the code
981       that is generated for a simple combined accessor:
982
983        *Foo::foo = sub {
984            return ($$field[${$_[0]}]) if (@_ == 1);
985            $$field[${$_[0]}] = $_[1];
986        };
987
988       And the corresponding code for an ":lvalue" combined accessor:
989
990        *Foo::foo = sub :lvalue {
991            my $rv = !Want::want_lvalue(0);
992            Want::rreturn($$field[${$_[0]}]) if ($rv && (@_ == 1));
993            my $assign;
994            if (my @args = Want::wantassign(1)) {
995                @_ = ($_[0], @args);
996                $assign = 1;
997            }
998            if (@_ > 1) {
999                $$field[${$_[0]}] = $_[1];
1000                Want::lnoreturn if $assign;
1001                Want::rreturn($$field[${$_[0]}]) if $rv;
1002            }
1003            ((@_ > 1) && (Want::wantref() eq 'OBJECT') &&
1004             !Scalar::Util::blessed($$field[${$_[0]}]))
1005                   ? $_[0] : $$field[${$_[0]}];
1006        };
1007

ALL-IN-ONE

1009       Parameter naming and accessor generation may be combined:
1010
1011        my @data :Field :All(data);
1012
1013       This is syntactic shorthand for:
1014
1015        my @data :Field :Arg(data) :Acc(data);
1016
1017       If you want the accessor to be ":lvalue", use:
1018
1019        my @data :Field :LV_All(data);
1020
1021       If standard accessors are desired, use:
1022
1023        my @data :Field :Std_All(data);
1024
1025       Attribute parameters affecting the set accessor may also be used.  For
1026       example, if you want standard accessors with an ":lvalue" set accessor:
1027
1028        my @data :Field :Std_All('Name' => 'data', 'Lvalue' => 1);
1029
1030       If you want a combined accessor that returns the old value on set
1031       operations:
1032
1033        my @data :Field :All('Name' => 'data', 'Ret' => 'Old');
1034
1035       And so on.
1036
1037       If you need to add attribute parameters that affect the ":Arg" portion
1038       (e.g., 'Default', 'Mandatory', etc.), then you cannot use ":All".  Fall
1039       back to using the separate attributes.  For example:
1040
1041        my @data :Field :Arg('Name' => 'data', 'Mand' => 1)
1042                        :Acc('Name' => 'data', 'Ret' => 'Old');
1043

PERMISSIONS

1045   Restricted and Private Accessors
1046       By default, automatically generated accessors, can be called at any
1047       time.  In other words, their access permission is public.
1048
1049       If desired, accessors can be made restricted - in which case they can
1050       only be called from within the class and any child classes in the
1051       hierarchy that are derived from it - or private - such that they can
1052       only be called from within the accessors' class.  Here are examples of
1053       the syntax for adding permissions:
1054
1055        my @data     :Field :Std('Name' => 'data',     'Permission' => 'private');
1056        my @info     :Field :Set('Name' => 'set_info', 'Perm' => 'restricted');
1057        my @internal :Field :Acc('Name' => 'internal', 'Private' => 1);
1058        my @state    :Field :Get('Name' => 'state',    'Restricted' => 1);
1059
1060       When creating a standard pair of get_/set_ accessors, the permission
1061       setting is applied to both accessors.  If different permissions are
1062       required on the two accessors, then you'll have to use separate ":Get"
1063       and ":Set" attributes on the field.
1064
1065        # Create a private set method
1066        #  and a restricted get method on the 'foo' field
1067        my @foo :Field
1068                :Set('Name' => 'set_foo', 'Priv' => 1)
1069                :Get('Name' => 'get_foo', 'Rest' => 1);
1070
1071        # Create a restricted set method
1072        #  and a public get method on the 'bar' field
1073        my %bar :Field
1074                :Set('Name' => 'set_bar', 'Perm' => 'restrict')
1075                :Get(get_bar);
1076
1077       "Permission" may be abbreviated to "Perm"; "Private" may be abbreviated
1078       to "Priv"; and "Restricted" may be abbreviated to "Restrict".
1079
1080   Restricted and Private Methods
1081       In the same vein as describe above, access to methods can be narrowed
1082       by use of ":Restricted" and ":Private" attributes.
1083
1084        sub foo :Restricted
1085        {
1086            my $self = shift;
1087            ...
1088        }
1089
1090       Without either of these attributes, most methods have public access.
1091       If desired, you may explicitly label them with the ":Public" attribute.
1092
1093   Exemptions
1094       It is also possible to specify classes that are exempt from the
1095       Restricted and Private access permissions (i.e., the method may be
1096       called from those classes as well):
1097
1098        my %foo :Field
1099                :Acc('Name' => 'foo', 'Perm' => 'Restrict(Exempt::Class)')
1100                :Get(get_bar);
1101
1102        sub bar :Private(Some::Class, Another::Class)
1103        {
1104            my $self = shift;
1105            ...
1106        }
1107
1108       An example of when this might be needed is with delegation mechanisms.
1109
1110   Hidden Methods
1111       For subroutines marked with the following attributes (most of which are
1112       discussed later in this document):
1113
1114       :ID
1115       :PreInit
1116       :Init
1117       :Replicate
1118       :Destroy
1119       :Automethod
1120       :Dumper
1121       :Pumper
1122       :MOD_*_ATTRS
1123       :FETCH_*_ATTRS
1124
1125       Object::InsideOut normally renders them uncallable (hidden) to class
1126       and application code (as they should normally only be needed by
1127       Object::InsideOut itself).  If needed, this behavior can be overridden
1128       by adding the "Public", "Restricted" or "Private" attribute parameters:
1129
1130        sub _init :Init(private)    # Callable from within this class
1131        {
1132            my ($self, $args) = @_;
1133
1134            ...
1135        }
1136
1137   Restricted and Private Classes
1138       Permission for object creation on a class can be narrowed by adding a
1139       ":Restricted" or ":Private" flag to its "use Object::InsideOut ..."
1140       declaration.  This basically adds ":Restricted/:Private" permissions on
1141       the "->new()" method for that class.  Exemptions are also supported.
1142
1143        package Foo; {
1144            use Object::InsideOut;
1145            ...
1146        }
1147
1148        package Bar; {
1149            use Object::InsideOut 'Foo', ':Restricted(Ping, Pong)';
1150            ...
1151        }
1152
1153       In the above, class "Bar" inherits from class "Foo", and its
1154       constructor is restricted to itself, classes that inherit from "Bar",
1155       and the classes "Ping" and "Pong".
1156
1157       As constructors are inherited, any class that inherits from "Bar" would
1158       also be a restricted class.  To overcome this, any child class would
1159       need to add its own permission declaration:
1160
1161        package Baz; {
1162            use Object::InsideOut qw/Bar :Private(My::Class)/;
1163            ...
1164        }
1165
1166       Here, class "Baz" inherits from class "Bar", and its constructor is
1167       restricted to itself (i.e., private) and class "My::Class".
1168
1169       Inheriting from a ":Private" class is permitted, but objects cannot be
1170       created for that class unless it has a permission declaration of its
1171       own:
1172
1173        package Zork; {
1174            use Object::InsideOut qw/:Public Baz/;
1175            ...
1176        }
1177
1178       Here, class "Zork" inherits from class "Baz", and its constructor has
1179       unrestricted access.  (In general, don't use the ":Public" declaration
1180       for a class except to overcome constructor permissions inherited from
1181       parent classes.)
1182

TYPE CHECKING

1184       Object::InsideOut can be directed to add type-checking code to the
1185       set/combined accessors it generates, and to perform type checking on
1186       object initialization parameters.
1187
1188   Field Type Checking
1189       Type checking for a field can be specified by adding the ":Type"
1190       attribute to the field declaration:
1191
1192        my @count :Field :Type(numeric);
1193
1194        my @objs :Field :Type(list(My::Class));
1195
1196       The ":Type" attribute results in type checking code being added to
1197       set/combined accessors generated by Object::InsideOut, and will perform
1198       type checking on object initialization parameters processed by the
1199       ":Arg" attribute.
1200
1201       Available Types are:
1202
1203       'scalar'
1204           Permits anything that is not a reference.
1205
1206       'numeric'
1207           Can also be specified as "Num" or "Number".  This uses
1208           Scalar::Util::looks_like_number() to test the input value.
1209
1210       'list' or 'array'
1211       'list(_subtype_)' or 'array(_subtype_)'
1212           This type permits an accessor to accept multiple values (which are
1213           then placed in an array ref) or a single array ref.
1214
1215           For object initialization parameters, it permits a single value
1216           (which is then placed in an array ref) or an array ref.
1217
1218           When specified, the contents of the resulting array ref are checked
1219           against the specified subtype:
1220
1221           'scalar'
1222               Same as for the basic type above.
1223
1224           'numeric'
1225               Same as for the basic type above.
1226
1227           A class name
1228               Same as for the basic type below.
1229
1230           A reference type
1231               Any reference type (in all caps) as returned by ref()).
1232
1233       'ARRAY_ref'
1234       'ARRAY_ref(_subtype_)'
1235           This specifies that only a single array reference is permitted.
1236           Can also be specified as "ARRAYref".
1237
1238           When specified, the contents of the array ref are checked against
1239           the specified subtype as per the above.
1240
1241       'HASH'
1242           This type permits an accessor to accept multiple "key => value"
1243           pairs (which are then placed in a hash ref) or a single hash ref.
1244
1245           For object initialization parameters, only a single ref is
1246           permitted.
1247
1248       'HASH_ref'
1249           This specifies that only a single hash reference is permitted.  Can
1250           also be specified as "HASHref".
1251
1252       A class name
1253           This permits only an object of the specified class, or one of its
1254           sub-classes (i.e., type checking is done using "->isa()").  For
1255           example, "My::Class".  The class name "UNIVERSAL" permits any
1256           object.  The class name "Object::InsideOut" permits any object
1257           generated by an Object::InsideOut class.
1258
1259       Other reference type
1260           This permits only a reference of the specified type (as returned by
1261           ref()).  The type must be specified in all caps.  For example,
1262           "CODE".
1263
1264       The ":Type" attribute can also be supplied with a code reference to
1265       provide custom type checking.  The code ref may either be in the form
1266       of an anonymous subroutine, or a fully-qualified subroutine name.  The
1267       result of executing the code ref on the input argument should be a
1268       boolean value.  Here's some examples:
1269
1270        package My::Class; {
1271            use Object::InsideOut;
1272
1273            # Type checking using an anonymous subroutine
1274            #  (This checks that the argument is an object)
1275            my @data :Field :Type(sub { Scalar::Util::blessed($_[0]) })
1276                            :Acc(data);
1277
1278            # Type checking using a fully-qualified subroutine name
1279            my @num  :Field :Type(\&My::Class::positive)
1280                            :Acc(num);
1281
1282            # The type checking subroutine may be made 'Private'
1283            sub positive :Private
1284            {
1285                return (Scalar::Util::looks_like_number($_[0]) &&
1286                        ($_[0] > 0));
1287            }
1288        }
1289
1290   Type Checking on ":Init" Parameters
1291       For object initialization parameters that are sent to the ":Init"
1292       subroutine during object initialization, the parameter's type can be
1293       specified in the ":InitArgs" hash for that parameter using the same
1294       types as specified in the previous section.  For example:
1295
1296        my %init_args :InitArgs = (
1297            'COUNT' => {
1298                'Type' => 'numeric',
1299            },
1300            'OBJS' => {
1301                'Type' => 'list(My::Class)',
1302            },
1303        );
1304
1305       One exception involves custom type checking:  If referenced in an
1306       ":InitArgs" hash, the type checking subroutine cannot be made
1307       ":Private":
1308
1309        package My::Class; {
1310            use Object::InsideOut;
1311
1312            sub check_type   # Cannot be :Private
1313            {
1314               ...
1315            }
1316
1317            my %init_args :InitArgs = (
1318                'ARG' => {
1319                    'Type' => \&check_type,
1320                },
1321            );
1322
1323            ...
1324        }
1325
1326       Also, as shown, it also doesn't have to be a fully-qualified name.
1327

CUMULATIVE METHODS

1329       Normally, methods with the same name in a class hierarchy are masked
1330       (i.e., overridden) by inheritance - only the method in the most-derived
1331       class is called.  With cumulative methods, this masking is removed, and
1332       the same-named method is called in each of the classes within the
1333       hierarchy.  The return results from each call (if any) are then
1334       gathered together into the return value for the original method call.
1335       For example,
1336
1337        package My::Class; {
1338            use Object::InsideOut;
1339
1340            sub what_am_i :Cumulative
1341            {
1342                my $self = shift;
1343
1344                my $ima = (ref($self) eq __PACKAGE__)
1345                            ? q/I was created as a /
1346                            : q/My top class is /;
1347
1348                return ($ima . __PACKAGE__);
1349            }
1350        }
1351
1352        package My::Foo; {
1353            use Object::InsideOut 'My::Class';
1354
1355            sub what_am_i :Cumulative
1356            {
1357                my $self = shift;
1358
1359                my $ima = (ref($self) eq __PACKAGE__)
1360                            ? q/I was created as a /
1361                            : q/I'm also a /;
1362
1363                return ($ima . __PACKAGE__);
1364            }
1365        }
1366
1367        package My::Child; {
1368            use Object::InsideOut 'My::Foo';
1369
1370            sub what_am_i :Cumulative
1371            {
1372                my $self = shift;
1373
1374                my $ima = (ref($self) eq __PACKAGE__)
1375                            ? q/I was created as a /
1376                            : q/I'm in class /;
1377
1378                return ($ima . __PACKAGE__);
1379            }
1380        }
1381
1382        package main;
1383
1384        my $obj = My::Child->new();
1385        my @desc = $obj->what_am_i();
1386        print(join("\n", @desc), "\n");
1387
1388       produces:
1389
1390        My top class is My::Class
1391        I'm also a My::Foo
1392        I was created as a My::Child
1393
1394       When called in a list context (as in the above), the return results of
1395       cumulative methods are accumulated, and returned as a list.
1396
1397       In a scalar context, a results object is returned that segregates the
1398       results by class for each of the cumulative method calls.  Through
1399       overloading, this object can then be dereferenced as an array, hash,
1400       string, number, or boolean.  For example, the above could be rewritten
1401       as:
1402
1403        my $obj = My::Child->new();
1404        my $desc = $obj->what_am_i();        # Results object
1405        print(join("\n", @{$desc}), "\n");   # Dereference as an array
1406
1407       The following uses hash dereferencing:
1408
1409        my $obj = My::Child->new();
1410        my $desc = $obj->what_am_i();
1411        while (my ($class, $value) = each(%{$desc})) {
1412            print("Class $class reports:\n\t$value\n");
1413        }
1414
1415       and produces:
1416
1417        Class My::Class reports:
1418                My top class is My::Class
1419        Class My::Child reports:
1420                I was created as a My::Child
1421        Class My::Foo reports:
1422                I'm also a My::Foo
1423
1424       As illustrated above, cumulative methods are tagged with the
1425       ":Cumulative" attribute (or ":Cumulative(top down)"), and propagate
1426       from the top down through the class hierarchy (i.e., from the parent
1427       classes down through the child classes).  If tagged with
1428       ":Cumulative(bottom up)", they will propagated from the object's class
1429       upward through the parent classes.
1430

CHAINED METHODS

1432       In addition to ":Cumulative", Object::InsideOut provides a way of
1433       creating methods that are chained together so that their return values
1434       are passed as input arguments to other similarly named methods in the
1435       same class hierarchy.  In this way, the chained methods act as though
1436       they were piped together.
1437
1438       For example, imagine you had a method called "format_name" that formats
1439       some text for display:
1440
1441        package Subscriber; {
1442            use Object::InsideOut;
1443
1444            sub format_name {
1445                my ($self, $name) = @_;
1446
1447                # Strip leading and trailing whitespace
1448                $name =~ s/^\s+//;
1449                $name =~ s/\s+$//;
1450
1451                return ($name);
1452            }
1453        }
1454
1455       And elsewhere you have a second class that formats the case of names:
1456
1457        package Person; {
1458            use Lingua::EN::NameCase qw(nc);
1459            use Object::InsideOut;
1460
1461            sub format_name
1462            {
1463                my ($self, $name) = @_;
1464
1465                # Attempt to properly case names
1466                return (nc($name));
1467            }
1468        }
1469
1470       And you decide that you'd like to perform some formatting of your own,
1471       and then have all the parent methods apply their own formatting.
1472       Normally, if you have a single parent class, you'd just call the method
1473       directly with "$self->SUPER::format_name($name)", but if you have more
1474       than one parent class you'd have to explicitly call each method
1475       directly:
1476
1477        package Customer; {
1478            use Object::InsideOut qw(Person Subscriber);
1479
1480            sub format_name
1481            {
1482                my ($self, $name) = @_;
1483
1484                # Compress all whitespace into a single space
1485                $name =~ s/\s+/ /g;
1486
1487                $name = $self->Subscriber::format_name($name);
1488                $name = $self->Person::format_name($name);
1489
1490                return $name;
1491            }
1492        }
1493
1494       With Object::InsideOut, you'd add the ":Chained" attribute to each
1495       class's "format_name" method, and the methods will be chained together
1496       automatically:
1497
1498        package Subscriber; {
1499            use Object::InsideOut;
1500
1501            sub format_name :Chained
1502            {
1503                my ($self, $name) = @_;
1504
1505                # Strip leading and trailing whitespace
1506                $name =~ s/^\s+//;
1507                $name =~ s/\s+$//;
1508
1509                return ($name);
1510            }
1511        }
1512
1513        package Person; {
1514            use Lingua::EN::NameCase qw(nc);
1515            use Object::InsideOut;
1516
1517            sub format_name :Chained
1518            {
1519                my ($self, $name) = @_;
1520
1521                # Attempt to properly case names
1522                return (nc($name));
1523            }
1524        }
1525
1526        package Customer; {
1527            use Object::InsideOut qw(Person Subscriber);
1528
1529            sub format_name :Chained
1530            {
1531                my ($self, $name) = @_;
1532
1533                # Compress all whitespace into a single space
1534                $name =~ s/\s+/ /g;
1535
1536                return ($name);
1537            }
1538        }
1539
1540       So passing in someone's name to "format_name" in "Customer" would cause
1541       leading and trailing whitespace to be removed, then the name to be
1542       properly cased, and finally whitespace to be compressed to a single
1543       space.  The resulting $name would be returned to the caller:
1544
1545        my ($name) = $obj->format_name($name_raw);
1546
1547       Unlike ":Cumulative" methods, ":Chained" methods always returns an
1548       array - even if there is only one value returned.  Therefore,
1549       ":Chained" methods should always be called in an array context, as
1550       illustrated above.
1551
1552       The default direction is to chain methods from the parent classes at
1553       the top of the class hierarchy down through the child classes.  You may
1554       use the attribute ":Chained(top down)" to make this more explicit.
1555
1556       If you label the method with the ":Chained(bottom up)" attribute, then
1557       the chained methods are called starting with the object's class and
1558       working upward through the parent classes in the class hierarchy,
1559       similar to how ":Cumulative(bottom up)" works.
1560

ARGUMENT MERGING

1562       As mentioned under "Object Creation", the "->new()" method can take
1563       parameters that are passed in as combinations of "key => value" pairs
1564       and/or hash refs:
1565
1566        my $obj = My::Class->new(
1567            'param_X' => 'value_X',
1568            'param_Y' => 'value_Y',
1569            {
1570                'param_A' => 'value_A',
1571                'param_B' => 'value_B',
1572            },
1573            {
1574                'param_Q' => 'value_Q',
1575            },
1576        );
1577
1578       The parameters are merged into a single hash ref before they are
1579       processed.
1580
1581       Adding the ":MergeArgs" attribute to your methods gives them a similar
1582       capability.  Your method will then get two arguments:  The object and a
1583       single hash ref of the merged arguments.  For example:
1584
1585        package Foo; {
1586            use Object::InsideOut;
1587
1588            ...
1589
1590            sub my_method :MergeArgs {
1591                my ($self, $args) = @_;
1592
1593                my $param = $args->{'param'};
1594                my $data  = $args->{'data'};
1595                my $flag  = $args->{'flag'};
1596                ...
1597            }
1598        }
1599
1600        package main;
1601
1602        my $obj = Foo->new(...);
1603
1604        $obj->my_method( { 'data' => 42,
1605                           'flag' => 'true' },
1606                         'param' => 'foo' );
1607

ARGUMENT VALIDATION

1609       A number of users have asked about argument validation for methods:
1610       <http://www.cpanforum.com/threads/3204>.  For this, I recommend using
1611       Params::Validate:
1612
1613        package Foo; {
1614            use Object::InsideOut;
1615            use Params::Validate ':all';
1616
1617            sub foo
1618            {
1619                my $self = shift;
1620                my %args = validate(@_, { bar => 1 });
1621                my $bar = $args{bar};
1622                ...
1623            }
1624        }
1625
1626       Using Attribute::Params::Validate, attributes are used for argument
1627       validation specifications:
1628
1629        package Foo; {
1630            use Object::InsideOut;
1631            use Attribute::Params::Validate;
1632
1633            sub foo :method :Validate(bar => 1)
1634            {
1635                my $self = shift;
1636                my %args = @_;
1637                my $bar = $args{bar};
1638                ...
1639            }
1640        }
1641
1642       Note that in the above, Perl's ":method" attribute (in all lowercase)
1643       is needed.
1644
1645       There is some incompatibility between Attribute::Params::Validate and
1646       some of Object::InsideOut's attributes.  Namely, you cannot use
1647       ":Validate" with ":Private", ":Restricted", ":Cumulative", ":Chained"
1648       or ":MergeArgs".  In these cases, use the "validate()" function from
1649       Params::Validate instead.
1650

AUTOMETHODS

1652       There are significant issues related to Perl's "AUTOLOAD" mechanism
1653       that cause it to be ill-suited for use in a class hierarchy. Therefore,
1654       Object::InsideOut implements its own ":Automethod" mechanism to
1655       overcome these problems.
1656
1657       Classes requiring "AUTOLOAD"-type capabilities must provided a
1658       subroutine labeled with the ":Automethod" attribute.  The ":Automethod"
1659       subroutine will be called with the object and the arguments in the
1660       original method call (the same as for "AUTOLOAD").  The ":Automethod"
1661       subroutine should return either a subroutine reference that implements
1662       the requested method's functionality, or else just end with "return;"
1663       to indicate that it doesn't know how to handle the request.
1664
1665       Using its own "AUTOLOAD" subroutine (which is exported to every class),
1666       Object::InsideOut walks through the class tree, calling each
1667       ":Automethod" subroutine, as needed, to fulfill an unimplemented method
1668       call.
1669
1670       The name of the method being called is passed as $_ instead of
1671       $AUTOLOAD, and is not prefixed with the class name.  If the
1672       ":Automethod" subroutine also needs to access the $_ from the caller's
1673       scope, it is available as $CALLER::_.
1674
1675       Automethods can also be made to act as "CUMULATIVE METHODS" or "CHAINED
1676       METHODS".  In these cases, the ":Automethod" subroutine should return
1677       two values: The subroutine ref to handle the method call, and a string
1678       designating the type of method.  The designator has the same form as
1679       the attributes used to designate ":Cumulative" and ":Chained" methods:
1680
1681        ':Cumulative'  or  ':Cumulative(top down)'
1682        ':Cumulative(bottom up)'
1683        ':Chained'     or  ':Chained(top down)'
1684        ':Chained(bottom up)'
1685
1686       The following skeletal code illustrates how an ":Automethod" subroutine
1687       could be structured:
1688
1689        sub _automethod :Automethod
1690        {
1691            my $self = shift;
1692            my @args = @_;
1693
1694            my $method_name = $_;
1695
1696            # This class can handle the method directly
1697            if (...) {
1698                my $handler = sub {
1699                    my $self = shift;
1700                    ...
1701                    return ...;
1702                };
1703
1704                ### OPTIONAL ###
1705                # Install the handler so it gets called directly next time
1706                # no strict refs;
1707                # *{__PACKAGE__.'::'.$method_name} = $handler;
1708                ################
1709
1710                return ($handler);
1711            }
1712
1713            # This class can handle the method as part of a chain
1714            if (...) {
1715                my $chained_handler = sub {
1716                    my $self = shift;
1717                    ...
1718                    return ...;
1719                };
1720
1721                return ($chained_handler, ':Chained');
1722            }
1723
1724            # This class cannot handle the method request
1725            return;
1726        }
1727
1728       Note: The OPTIONAL code above for installing the generated handler as a
1729       method should not be used with ":Cumulative" or ":Chained" automethods.
1730

OBJECT SERIALIZATION

1732   Basic Serialization
1733       my $array_ref = $obj->dump();
1734       my $string = $obj->dump(1);
1735           Object::InsideOut exports a method called "->dump()" to each class
1736           that returns either a Perl or a string representation of the object
1737           that invokes the method.
1738
1739           The Perl representation is returned when "->dump()" is called
1740           without arguments.  It consists of an array ref whose first element
1741           is the name of the object's class, and whose second element is a
1742           hash ref containing the object's data.  The object data hash ref
1743           contains keys for each of the classes that make up the object's
1744           hierarchy. The values for those keys are hash refs containing
1745           "key => value" pairs for the object's fields.  For example:
1746
1747            [
1748              'My::Class::Sub',
1749              {
1750                'My::Class' => {
1751                                 'data' => 'value'
1752                               },
1753                'My::Class::Sub' => {
1754                                      'life' => 42
1755                                    }
1756              }
1757            ]
1758
1759           The name for an object field (data and life in the example above)
1760           can be specified by adding the ":Name" attribute to the field:
1761
1762            my @life :Field :Name(life);
1763
1764           If the ":Name" attribute is not used, then the name for a field
1765           will be either the name associated with an ":All" or ":Arg"
1766           attribute, its get method name, its set method name, or, failing
1767           all that, a string of the form "ARRAY(0x...)" or "HASH(0x...)".
1768
1769           When called with a true argument, "->dump()" returns a string
1770           version of the Perl representation using Data::Dumper.
1771
1772           Note that using Data::Dumper directly on an inside-out object will
1773           not produce the desired results (it'll just output the contents of
1774           the scalar ref).  Also, if inside-out objects are stored inside
1775           other structures, a dump of those structures will not contain the
1776           contents of the object's fields.
1777
1778           In the event of a method naming conflict, the "->dump()" method can
1779           be called using its fully-qualified name:
1780
1781            my $dump = $obj->Object::InsideOut::dump();
1782
1783       my $obj = Object::InsideOut->pump($data);
1784           "Object::InsideOut->pump()" takes the output from the "->dump()"
1785           method, and returns an object that is created using that data.  If
1786           $data is the array ref returned by using "$obj->dump()", then the
1787           data is inserted directly into the corresponding fields for each
1788           class in the object's class hierarchy.  If $data is the string
1789           returned by using "$obj->dump(1)", then it is "eval"ed to turn it
1790           into an array ref, and then processed as above.
1791
1792           Caveats: If any of an object's fields are dumped to field name keys
1793           of the form "ARRAY(0x...)" or "HASH(0x...)" (see above), then the
1794           data will not be reloadable using "Object::InsideOut->pump()".  To
1795           overcome this problem, the class developer must either add ":Name"
1796           attributes to the ":Field" declarations (see above), or provide a
1797           ":Dumper"/":Pumper" pair of subroutines as described below.
1798
1799           Dynamically altering a class (e.g., using ->create_field() after
1800           objects have been dumped will result in "undef" fields when pumped
1801           back in regardless of whether or not the added fields have
1802           defaults.
1803
1804           Modifying the output from "->dump()", and then feeding it into
1805           "Object::InsideOut->pump()" will work, but is not specifically
1806           supported.  If you know what you're doing, fine, but you're on your
1807           own.
1808
1809       ":Dumper" Subroutine Attribute
1810           If a class requires special processing to dump its data, then it
1811           can provide a subroutine labeled with the ":Dumper" attribute.
1812           This subroutine will be sent the object that is being dumped.  It
1813           may then return any type of scalar the developer deems appropriate.
1814           Usually, this would be a hash ref containing "key => value" pairs
1815           for the object's fields.  For example:
1816
1817            my @data :Field;
1818
1819            sub _dump :Dumper
1820            {
1821                my $obj = $_[0];
1822
1823                my %field_data;
1824                $field_data{'data'} = $data[$$obj];
1825
1826                return (\%field_data);
1827            }
1828
1829           Just be sure not to call your ":Dumper" subroutine "dump" as that
1830           is the name of the dump method exported by Object::InsideOut as
1831           explained above.
1832
1833       ":Pumper" Subroutine Attribute
1834           If a class supplies a ":Dumper" subroutine, it will most likely
1835           need to provide a complementary ":Pumper" labeled subroutine that
1836           will be used as part of creating an object from dumped data using
1837           "Object::InsideOut->pump()".  The subroutine will be supplied the
1838           new object that is being created, and whatever scalar was returned
1839           by the ":Dumper" subroutine.  The corresponding ":Pumper" for the
1840           example ":Dumper" above would be:
1841
1842            sub _pump :Pumper
1843            {
1844                my ($obj, $field_data) = @_;
1845
1846                $obj->set(\@data, $field_data->{'data'});
1847            }
1848
1849   Storable
1850       Object::InsideOut also supports object serialization using the Storable
1851       module.  There are two methods for specifying that a class can be
1852       serialized using Storable.  The first method involves adding Storable
1853       to the Object::InsideOut declaration in your package:
1854
1855        package My::Class; {
1856            use Object::InsideOut qw(Storable);
1857            ...
1858        }
1859
1860       and adding "use Storable;" in your application.  Then you can use the
1861       "->store()" and "->freeze()" methods to serialize your objects, and the
1862       "retrieve()" and "thaw()" subroutines to de-serialize them.
1863
1864        package main;
1865        use Storable;
1866        use My::Class;
1867
1868        my $obj = My::Class->new(...);
1869        $obj->store('/tmp/object.dat');
1870        ...
1871        my $obj2 = retrieve('/tmp/object.dat');
1872
1873       The other method of specifying Storable serialization involves setting
1874       a "::storable" variable inside a "BEGIN" block for the class prior to
1875       its use:
1876
1877        package main;
1878        use Storable;
1879
1880        BEGIN {
1881            $My::Class::storable = 1;
1882        }
1883        use My::Class;
1884
1885       NOTE: The caveats discussed above for the "->pump()" method are also
1886       applicable when using the Storable module.
1887

OBJECT COERCION

1889       Object::InsideOut provides support for various forms of object coercion
1890       through the overload mechanism.  For instance, if you want an object to
1891       be usable directly in a string, you would supply a subroutine in your
1892       class labeled with the ":Stringify" attribute:
1893
1894        sub as_string :Stringify
1895        {
1896            my $self = $_[0];
1897            my $string = ...;
1898            return ($string);
1899        }
1900
1901       Then you could do things like:
1902
1903        print("The object says, '$obj'\n");
1904
1905       For a boolean context, you would supply:
1906
1907        sub as_bool :Boolify
1908        {
1909            my $self = $_[0];
1910            my $true_or_false = ...;
1911            return ($true_or_false);
1912        }
1913
1914       and use it in this manner:
1915
1916        if (! defined($obj)) {
1917            # The object is undefined
1918            ....
1919
1920        } elsif (! $obj) {
1921            # The object returned a false value
1922            ...
1923        }
1924
1925       The following coercion attributes are supported:
1926
1927       :Stringify
1928       :Numerify
1929       :Boolify
1930       :Arrayify
1931       :Hashify
1932       :Globify
1933       :Codify
1934
1935       Coercing an object to a scalar (":Scalarify") is not supported as $$obj
1936       is the ID of the object and cannot be overridden.
1937

CLONING

1939   Object Cloning
1940       Copies of objects can be created using the "->clone()" method which is
1941       exported by Object::InsideOut to each class:
1942
1943        my $obj2 = $obj->clone();
1944
1945       When called without arguments, "->clone()" creates a shallow copy of
1946       the object, meaning that any complex data structures (i.e., array, hash
1947       or scalar refs) stored in the object will be shared with its clone.
1948
1949       Calling "->clone()" with a true argument:
1950
1951        my $obj2 = $obj->clone(1);
1952
1953       creates a deep copy of the object such that internally held array, hash
1954       or scalar refs are replicated and stored in the newly created clone.
1955
1956       Deep cloning can also be controlled at the field level, and is covered
1957       in the next section.
1958
1959       Note that cloning does not clone internally held objects.  For example,
1960       if $foo contains a reference to $bar, a clone of $foo will also contain
1961       a reference to $bar; not a clone of $bar.  If such behavior is needed,
1962       it must be provided using a :Replicate subroutine.
1963
1964   Field Cloning
1965       Object cloning can be controlled at the field level such that specified
1966       fields are deeply copied when "->clone()" is called without any
1967       arguments.  This is done by adding the ":Deep" attribute to the field:
1968
1969        my @data :Field :Deep;
1970

WEAK FIELDS

1972       Frequently, it is useful to store weakened references to data or
1973       objects in a field.  Such a field can be declared as ":Weak" so that
1974       data (i.e., references) set via Object::InsideOut generated accessors,
1975       parameter processing using ":Arg", the "->set()" method, etc., will
1976       automatically be weakened after being stored in the field array/hash.
1977
1978        my @data :Field :Weak;
1979
1980       NOTE: If data in a weak field is set directly (i.e., the "->set()"
1981       method is not used), then weaken() must be invoked on the stored
1982       reference afterwards:
1983
1984        $self->set(\@field, $data);
1985        Scalar::Util::weaken($field[$$self]);
1986
1987       (This is another reason why the "->set()" method is recommended for
1988       setting field data within class code.)
1989

DYNAMIC FIELD CREATION

1991       Normally, object fields are declared as part of the class code.
1992       However, some classes may need the capability to create object fields
1993       on-the-fly, for example, as part of an ":Automethod".
1994       Object::InsideOut provides a class method for this:
1995
1996        # Dynamically create a hash field with standard accessors
1997        My::Class->create_field('%'.$fld, ":Std($fld)");
1998
1999       The first argument is the class into which the field will be added.
2000       The second argument is a string containing the name of the field
2001       preceded by either a "@" or "%" to declare an array field or hash
2002       field, respectively.  The remaining string arguments should be
2003       attributes declaring accessors and the like.  The ":Field" attribute is
2004       assumed, and does not need to be added to the attribute list.  For
2005       example:
2006
2007        My::Class->create_field('@data', ":Type(numeric)",
2008                                         ":Acc(data)");
2009
2010        My::Class->create_field('@obj', ":Type(Some::Class)",
2011                                        ":Acc(obj)",
2012                                        ":Weak");
2013
2014       Field creation will fail if you try to create an array field within a
2015       class whose hierarchy has been declared :hash_only.
2016
2017       Here's an example of an ":Automethod" subroutine that uses dynamic
2018       field creation:
2019
2020        package My::Class; {
2021            use Object::InsideOut;
2022
2023            sub _automethod :Automethod
2024            {
2025                my $self = $_[0];
2026                my $class = ref($self) || $self;
2027                my $method = $_;
2028
2029                # Extract desired field name from get_/set_ method name
2030                my ($fld_name) = $method =~ /^[gs]et_(.*)$/;
2031                if (! $fld_name) {
2032                    return;    # Not a recognized method
2033                }
2034
2035                # Create the field and its standard accessors
2036                $class->create_field('@'.$fld_name, ":Std($fld_name)");
2037
2038                # Return code ref for newly created accessor
2039                no strict 'refs';
2040                return *{$class.'::'.$method}{'CODE'};
2041            }
2042        }
2043

RUNTIME INHERITANCE

2045       The class method "->add_class()" provides the capability to dynamically
2046       add classes to a class hierarchy at runtime.
2047
2048       For example, suppose you had a simple state class:
2049
2050        package Trait::State; {
2051            use Object::InsideOut;
2052
2053            my %state :Field :Set(state);
2054        }
2055
2056       This could be added to another class at runtime using:
2057
2058        My::Class->add_class('Trait::State');
2059
2060       This permits, for example, application code to dynamically modify a
2061       class without having it create an actual sub-class.
2062

PREPROCESSING

2064   Parameter Preprocessing
2065       You can specify a code ref (either in the form of an anonymous
2066       subroutine, or a subroutine name) for an object initialization
2067       parameter that will be called on that parameter prior to taking any of
2068       the other parameter actions described above.  Here's an example:
2069
2070        package My::Class; {
2071            use Object::InsideOut;
2072
2073            # The parameter preprocessing subroutine
2074            sub preproc
2075            {
2076                my ($class, $param, $spec, $obj, $value) = @_;
2077
2078                # Preform parameter preprocessing
2079                ...
2080
2081                # Return result
2082                return ...;
2083            }
2084
2085            my @data :Field
2086                     :Arg('Name' => 'DATA', 'Preprocess' => \&My::Class::preproc);
2087
2088            my %init_args :InitArgs = (
2089                'PARAM' => {
2090                    'Preprocess' => \&preproc,
2091                },
2092            );
2093
2094            ...
2095        }
2096
2097       When used in the ":Arg" attribute, the subroutine name must be fully-
2098       qualified, as illustrated.  Further, if not referenced in the
2099       ":InitArgs" hash, the preprocessing subroutine can be given the
2100       ":Private" attribute.
2101
2102       As the above illustrates, the parameter preprocessing subroutine is
2103       sent five arguments:
2104
2105       ·   The name of the class associated with the parameter
2106
2107           This would be "My::Class" in the example above.
2108
2109       ·   The name of the parameter
2110
2111           Either "DATA" or "PARAM" in the example above.
2112
2113       ·   A hash ref of the parameter's specifiers
2114
2115           This is either a hash ref containing the ":Arg" attribute
2116           parameters, or the hash ref paired to the parameter's key in the
2117           ":InitArgs" hash.
2118
2119       ·   The object being initialized
2120
2121       ·   The parameter's value
2122
2123           This is the value assigned to the parameter in the "->new()"
2124           method's argument list.  If the parameter was not provided to
2125           "->new()", then "undef" will be sent.
2126
2127       The return value of the preprocessing subroutine will then be assigned
2128       to the parameter.
2129
2130       Be careful about what types of data the preprocessing subroutine tries
2131       to make use of "external" to the arguments supplied.  For instance,
2132       because the order of parameter processing is not specified, the
2133       preprocessing subroutine cannot rely on whether or not some other
2134       parameter is set.  Such processing would need to be done in the ":Init"
2135       subroutine.  It can, however, make use of object data set by classes
2136       higher up in the class hierarchy.  (That is why the object is provided
2137       as one of the arguments.)
2138
2139       Possible uses for parameter preprocessing include:
2140
2141       ·   Overriding the supplied value (or even deleting it by returning
2142           "undef")
2143
2144       ·   Providing a dynamically-determined default value
2145
2146       Preprocess may be abbreviated to Preproc or Pre.
2147
2148   Set Accessor Preprocessing
2149       You can specify a code ref (either in the form of an anonymous
2150       subroutine, or a fully-qualified subroutine name) for a set/combined
2151       accessor that will be called on the arguments supplied to the accessor
2152       prior to its taking the usual actions of type checking and adding the
2153       data to the field.  Here's an example:
2154
2155        package My::Class; {
2156            use Object::InsideOut;
2157
2158            my @data :Field
2159                     :Acc('Name' => 'data', 'Preprocess' => \&My::Class::preproc);
2160
2161            # The set accessor preprocessing subroutine may be made 'Private'
2162            sub preproc :Private
2163            {
2164                my ($self, $field, @args) = @_;
2165
2166                # Preform preprocessing on the accessor's arguments
2167                ...
2168
2169                # Return result
2170                return ...;
2171            }
2172        }
2173
2174       As the above illustrates, the accessor preprocessing subroutine is sent
2175       the following arguments:
2176
2177       ·   The object used to invoke the accessor
2178
2179       ·   A reference to the field associated with the accessor
2180
2181       ·   The argument(s) sent to the accessor
2182
2183           There will always be at least one argument.
2184
2185       Usually, the preprocessing subroutine would return just a single value.
2186       For fields declared as type "List", multiple values may be returned.
2187
2188       Following preprocessing, the set accessor will operate on whatever
2189       value(s) are returned by the preprocessing subroutine.
2190

SPECIAL PROCESSING

2192   Object ID
2193       By default, the ID of an object is derived from a sequence counter for
2194       the object's class hierarchy.  This should suffice for nearly all cases
2195       of class development.  If there is a special need for the module code
2196       to control the object ID (see Math::Random::MT::Auto as an example),
2197       then a subroutine labelled with the ":ID" attribute can be specified:
2198
2199        sub _id :ID
2200        {
2201            my $class = $_[0];
2202
2203            # Generate/determine a unique object ID
2204            ...
2205
2206            return ($id);
2207        }
2208
2209       The ID returned by your subroutine can be any kind of regular scalar
2210       (e.g., a string or a number).  However, if the ID is something other
2211       than a low-valued integer, then you will have to architect all your
2212       classes using hashes for the object fields.  See "HASH ONLY CLASSES"
2213       for details.
2214
2215       Within any class hierarchy, only one class may specify an ":ID"
2216       subroutine.
2217
2218   Object Replication
2219       Object replication occurs explicitly when the "->clone()" method is
2220       called on an object, and implicitly when threads are created in a
2221       threaded application.  In nearly all cases, Object::InsideOut will take
2222       care of all the details for you.
2223
2224       In rare cases, a class may require special handling for object
2225       replication.  It must then provide a subroutine labeled with the
2226       ":Replicate" attribute.  This subroutine will be sent three arguments:
2227       The parent and the cloned objects, and a flag:
2228
2229        sub _replicate :Replicate
2230        {
2231            my ($parent, $clone, $flag) = @_;
2232
2233            # Special object replication processing
2234            if ($clone eq 'CLONE') {
2235               # Handling for thread cloning
2236               ...
2237            } elsif ($clone eq 'deep') {
2238               # Deep copy of the parent
2239               ...
2240            } else {
2241               # Shallow copying
2242               ...
2243            }
2244        }
2245
2246       In the case of thread cloning, $flag will be set to the 'CLONE', and
2247       the $parent object is just a non-blessed anonymous scalar reference
2248       that contains the ID for the object in the parent thread.
2249
2250       When invoked via the "->clone()" method, $flag will be either an empty
2251       string which denotes that a shallow copy is being produced for the
2252       clone, or $flag will be set to 'deep' indicating a deep copy is being
2253       produced.
2254
2255       The ":Replicate" subroutine only needs to deal with the special
2256       replication processing needed by the object:  Object::InsideOut will
2257       handle all the other details.
2258
2259   Object Destruction
2260       Object::InsideOut exports a "DESTROY" method to each class that deletes
2261       an object's data from the object field arrays (hashes).  If a class
2262       requires additional destruction processing (e.g., closing filehandles),
2263       then it must provide a subroutine labeled with the ":Destroy"
2264       attribute.  This subroutine will be sent the object that is being
2265       destroyed:
2266
2267        sub _destroy :Destroy
2268        {
2269            my $obj = $_[0];
2270
2271            # Special object destruction processing
2272        }
2273
2274       The ":Destroy" subroutine only needs to deal with the special
2275       destruction processing:  The "DESTROY" method will handle all the other
2276       details of object destruction.
2277

FOREIGN CLASS INHERITANCE

2279       Object::InsideOut supports inheritance from foreign (i.e.,
2280       non-Object::InsideOut) classes.  This means that your classes can
2281       inherit from other Perl class, and access their methods from your own
2282       objects.
2283
2284       One method of declaring foreign class inheritance is to add the class
2285       name to the Object::InsideOut declaration inside your package:
2286
2287        package My::Class; {
2288            use Object::InsideOut qw(Foreign::Class);
2289            ...
2290        }
2291
2292       This allows you to access the foreign class's static (i.e., class)
2293       methods from your own class.  For example, suppose "Foreign::Class" has
2294       a class method called "foo".  With the above, you can access that
2295       method using "My::Class->foo()" instead.
2296
2297       Multiple foreign inheritance is supported, as well:
2298
2299        package My::Class; {
2300            use Object::InsideOut qw(Foreign::Class Other::Foreign::Class);
2301            ...
2302        }
2303
2304       $self->inherit($obj, ...);
2305           To use object methods from foreign classes, an object must inherit
2306           from an object of that class.  This would normally be done inside a
2307           class's ":Init" subroutine:
2308
2309            package My::Class; {
2310                use Object::InsideOut qw(Foreign::Class);
2311
2312                sub init :Init
2313                {
2314                    my ($self, $args) = @_;
2315
2316                    my $foreign_obj = Foreign::Class->new(...);
2317                    $self->inherit($foreign_obj);
2318                }
2319            }
2320
2321           Thus, with the above, if "Foreign::Class" has an object method
2322           called "bar", you can call that method from your own objects:
2323
2324            package main;
2325
2326            my $obj = My::Class->new();
2327            $obj->bar();
2328
2329           Object::InsideOut's "AUTOLOAD" subroutine handles the dispatching
2330           of the "->bar()" method call using the internally held inherited
2331           object (in this case, $foreign_obj).
2332
2333           Multiple inheritance is supported, as well:  You can call the
2334           "->inherit()" method multiple times, or make just one call with all
2335           the objects to be inherited from.
2336
2337           "->inherit()" is a restricted method.  In other words, you cannot
2338           use it on an object outside of code belonging to the object's class
2339           tree (e.g., you can't call it from application code).
2340
2341           In the event of a method naming conflict, the "->inherit()" method
2342           can be called using its fully-qualified name:
2343
2344            $self->Object::InsideOut::inherit($obj);
2345
2346       my @objs = $self->heritage();
2347       my $obj = $self->heritage($class);
2348       my @objs = $self->heritage($class1, $class2, ...);
2349           Your class code can retrieve any inherited objects using the
2350           "->heritage()" method. When called without any arguments, it
2351           returns a list of any objects that were stored by the calling class
2352           using the calling object.  In other words, if class "My::Class"
2353           uses object $obj to store foreign objects $fobj1 and $fobj2, then
2354           later on in class "My::Class", "$obj->heritage()" will return
2355           $fobj1 and $fobj2.
2356
2357           "->heritage()" can also be called with one or more class name
2358           arguments.  In this case, only objects of the specified class(es)
2359           are returned.
2360
2361           In the event of a method naming conflict, the "->heritage()" method
2362           can be called using its fully-qualified name:
2363
2364            my @objs = $self->Object::InsideOut::heritage();
2365
2366       $self->disinherit($class [, ...])
2367       $self->disinherit($obj [, ...])
2368           The "->disinherit()" method disassociates (i.e., deletes) the
2369           inheritance of foreign object(s) from an object.  The foreign
2370           objects may be specified by class, or using the actual inherited
2371           object (retrieved via "->heritage()", for example).
2372
2373           The call is only effective when called inside the class code that
2374           established the initial inheritance.  In other words, if an
2375           inheritance is set up inside a class, then disinheritance can only
2376           be done from inside that class.
2377
2378           In the event of a method naming conflict, the "->disinherit()"
2379           method can be called using its fully-qualified name:
2380
2381            $self->Object::InsideOut::disinherit($obj [, ...])
2382
2383       NOTE:  With foreign inheritance, you only have access to class and
2384       object methods.  The encapsulation of the inherited objects is strong,
2385       meaning that only the class where the inheritance takes place has
2386       direct access to the inherited object.  If access to the inherited
2387       objects themselves, or their internal hash fields (in the case of
2388       blessed hash objects), is needed outside the class, then you'll need to
2389       write your own accessors for that.
2390
2391       LIMITATION:  You cannot use fully-qualified method names to access
2392       foreign methods (when encapsulated foreign objects are involved).
2393       Thus, the following will not work:
2394
2395        my $obj = My::Class->new();
2396        $obj->Foreign::Class::bar();
2397
2398       Normally, you shouldn't ever need to do the above:  "$obj->bar()" would
2399       suffice.
2400
2401       The only time this may be an issue is when the native class overrides
2402       an inherited foreign class's method (e.g., "My::Class" has its own
2403       "->bar()" method).  Such overridden methods are not directly callable.
2404       If such overriding is intentional, then this should not be an issue:
2405       No one should be writing code that tries to by-pass the override.
2406       However, if the overriding is accidentally, then either the native
2407       method should be renamed, or the native class should provide a wrapper
2408       method so that the functionality of the overridden method is made
2409       available under a different name.
2410
2411   "use base" and Fully-qualified Method Names
2412       The foreign inheritance methodology handled by the above is predicated
2413       on non-Object::InsideOut classes that generate their own objects and
2414       expect their object methods to be invoked via those objects.
2415
2416       There are exceptions to this rule:
2417
2418       1. Foreign object methods that expect to be invoked via the inheriting
2419       class's object, or foreign object methods that don't care how they are
2420       invoked (i.e., they don't make reference to the invoking object).
2421           This is the case where a class provides auxiliary methods for your
2422           objects, but from which you don't actually create any objects
2423           (i.e., there is no corresponding foreign object, and
2424           "$obj->inherit($foreign)" is not used.)
2425
2426           In this case, you can either:
2427
2428           a. Declare the foreign class using the standard method (i.e.,
2429           "use Object::InsideOut qw(Foreign::Class);"), and invoke its
2430           methods using their full path (e.g.,
2431           "$obj->Foreign::Class::method();"); or
2432
2433           b. You can use the base pragma so that you don't have to use the
2434           full path for foreign methods.
2435
2436            package My::Class; {
2437                use Object::InsideOut;
2438                use base 'Foreign::Class';
2439                ...
2440            }
2441
2442           The former scheme is faster.
2443
2444       2. Foreign class methods that expect to be invoked via the inheriting
2445       class.
2446           As with the above, you can either invoke the class methods using
2447           their full path (e.g., "My::Class->Foreign::Class::method();"), or
2448           you can "use base" so that you don't have to use the full path.
2449           Again, using the full path is faster.
2450
2451           Class::Singleton is an example of this type of class.
2452
2453       3. Class methods that don't care how they are invoked (i.e., they don't
2454       make reference to the invoking class).
2455           In this case, you can either use
2456           "use Object::InsideOut qw(Foreign::Class);" for consistency, or use
2457           "use base qw(Foreign::Class);" if (slightly) better performance is
2458           needed.
2459
2460       If you're not familiar with the inner workings of the foreign class
2461       such that you don't know if or which of the above exceptions applies,
2462       then the formulaic approach would be to first use the documented method
2463       for foreign inheritance (i.e.,
2464       "use Object::InsideOut qw(Foreign::Class);").  If that works, then I
2465       strongly recommend that you just use that approach unless you have a
2466       good reason not to.  If it doesn't work, then try "use base".
2467

INTROSPECTION

2469       For Perl 5.8.0 and later, Object::InsideOut provides an introspection
2470       API that allow you to obtain metadata on a class's hierarchy,
2471       constructor parameters, and methods.
2472
2473       my $meta = My::Class->meta();
2474       my $meta = $obj->meta();
2475           The "->meta()" method, which is exported by Object::InsideOut to
2476           each class, returns an Object::InsideOut::Metadata object which can
2477           then be queried for information about the invoking class or
2478           invoking object's class:
2479
2480            # Get an object's class hierarchy
2481            my @classes = $obj->meta()->get_classes();
2482
2483            # Get info on the args for a class's constructor (i.e., ->new() parameters)
2484            my %args = My::Class->meta()->get_args();
2485
2486            # Get info on the methods that can be called by an object
2487            my %methods = $obj->meta()->get_methods();
2488
2489       My::Class->isa();
2490       $obj->isa();
2491           When called in an array context, calling "->isa()" without any
2492           arguments on an Object::InsideOut class or object returns a list of
2493           the classes in the class hierarchy for that class or object, and is
2494           equivalent to:
2495
2496            my @classes = $obj->meta()->get_classes();
2497
2498           When called in a scalar context, it returns an array ref containing
2499           the classes.
2500
2501       My::Class->can();
2502       $obj->can();
2503           When called in an array context, calling "->can()" without any
2504           arguments on an Object::InsideOut class or object returns a list of
2505           the method names for that class or object, and is equivalent to:
2506
2507            my %methods = $obj->meta()->get_methods();
2508            my @methods = keys(%methods);
2509
2510           When called in a scalar context, it returns an array ref containing
2511           the method names.
2512
2513       See Object::InsideOut::Metadata for more details.
2514

THREAD SUPPORT

2516       For Perl 5.8.1 and later, Object::InsideOut fully supports threads
2517       (i.e., is thread safe), and supports the sharing of Object::InsideOut
2518       objects between threads using threads::shared.
2519
2520       To use Object::InsideOut in a threaded application, you must put
2521       "use threads;" at the beginning of the application.  (The use of
2522       "require threads;" after the program is running is not supported.)  If
2523       object sharing is to be utilized, then "use threads::shared;" should
2524       follow.
2525
2526       If you just "use threads;", then objects from one thread will be copied
2527       and made available in a child thread.
2528
2529       The addition of "use threads::shared;" in and of itself does not alter
2530       the behavior of Object::InsideOut objects.  The default behavior is to
2531       not share objects between threads (i.e., they act the same as with
2532       "use threads;" alone).
2533
2534       To enable the sharing of objects between threads, you must specify
2535       which classes will be involved with thread object sharing.  There are
2536       two methods for doing this.  The first involves setting a "::shared"
2537       variable (inside a "BEGIN" block) for the class prior to its use:
2538
2539        use threads;
2540        use threads::shared;
2541
2542        BEGIN {
2543            $My::Class::shared = 1;
2544        }
2545        use My::Class;
2546
2547       The other method is for a class to add a ":SHARED" flag to its
2548       "use Object::InsideOut ..." declaration:
2549
2550        package My::Class; {
2551            use Object::InsideOut ':SHARED';
2552            ...
2553        }
2554
2555       When either sharing flag is set for one class in an object hierarchy,
2556       then all the classes in the hierarchy are affected.
2557
2558       If a class cannot support thread object sharing (e.g., one of the
2559       object fields contains code refs [which Perl cannot share between
2560       threads]), it should specifically declare this fact:
2561
2562        package My::Class; {
2563            use Object::InsideOut ':NOT_SHARED';
2564            ...
2565        }
2566
2567       However, you cannot mix thread object sharing classes with non-sharing
2568       classes in the same class hierarchy:
2569
2570        use threads;
2571        use threads::shared;
2572
2573        package My::Class; {
2574            use Object::InsideOut ':SHARED';
2575            ...
2576        }
2577
2578        package Other::Class; {
2579            use Object::InsideOut ':NOT_SHARED';
2580            ...
2581        }
2582
2583        package My::Derived; {
2584            use Object::InsideOut qw(My::Class Other::Class);   # ERROR!
2585            ...
2586        }
2587
2588       Here is a complete example with thread object sharing enabled:
2589
2590        use threads;
2591        use threads::shared;
2592
2593        package My::Class; {
2594            use Object::InsideOut ':SHARED';
2595
2596            # One list-type field
2597            my @data :Field :Type(list) :Acc(data);
2598        }
2599
2600        package main;
2601
2602        # New object
2603        my $obj = My::Class->new();
2604
2605        # Set the object's 'data' field
2606        $obj->data(qw(foo bar baz));
2607
2608        # Print out the object's data
2609        print(join(', ', @{$obj->data()}), "\n");       # "foo, bar, baz"
2610
2611        # Create a thread and manipulate the object's data
2612        my $rc = threads->create(
2613                sub {
2614                    # Read the object's data
2615                    my $data = $obj->data();
2616                    # Print out the object's data
2617                    print(join(', ', @{$data}), "\n");  # "foo, bar, baz"
2618                    # Change the object's data
2619                    $obj->data(@$data[1..2], 'zooks');
2620                    # Print out the object's modified data
2621                    print(join(', ', @{$obj->data()}), "\n");  # "bar, baz, zooks"
2622                    return (1);
2623                }
2624            )->join();
2625
2626        # Show that changes in the object are visible in the parent thread
2627        # I.e., this shows that the object was indeed shared between threads
2628        print(join(', ', @{$obj->data()}), "\n");       # "bar, baz, zooks"
2629

HASH ONLY CLASSES

2631       For performance considerations, it is recommended that arrays be used
2632       for class fields whenever possible.  The only time when hash-bases
2633       fields are required is when a class must provide its own object ID, and
2634       those IDs are something other than low-valued integers.  In this case,
2635       hashes must be used for fields not only in the class that defines the
2636       object ID subroutine, but also in every class in any class hierarchy
2637       that include such a class.
2638
2639       The hash only requirement can be enforced by adding the ":HASH_ONLY"
2640       flag to a class's "use Object::InsideOut ..." declaration:
2641
2642        package My::Class; {
2643            use Object::InsideOut ':hash_only';
2644
2645            ...
2646        }
2647
2648       This will cause Object::Inside to check every class in any class
2649       hierarchy that includes such flagged classes to make sure their fields
2650       are hashes and not arrays.  It will also fail any ->create_field() call
2651       that tries to create an array-based field in any such class.
2652

SECURITY

2654       In the default case where Object::InsideOut provides object IDs that
2655       are sequential integers, it is possible to hack together a fake
2656       Object::InsideOut object, and so gain access to another object's data:
2657
2658        my $fake = bless(\do{my $scalar}, 'Some::Class');
2659        $$fake = 86;   # ID of another object
2660        my $stolen = $fake->get_data();
2661
2662       Why anyone would try to do this is unknown.  How this could be used for
2663       any sort of malicious exploitation is also unknown.  However, if
2664       preventing this sort of security issue is a requirement, it can be
2665       accomplished by adding the ":SECURE" flag to a class's
2666       "use Object::InsideOut ..." declaration:
2667
2668        package My::Class; {
2669            use Object::InsideOut ':SECURE';
2670
2671            ...
2672        }
2673
2674       This places the module "Object::InsideOut::Secure" in the class
2675       hierarchy.  Object::InsideOut::Secure provides an :ID subroutine that
2676       generates random integers for object IDs, thus preventing other code
2677       from being able to create fake objects by guessing at IDs.
2678
2679       Using ":SECURE" mode requires Math::Random::MT::Auto (v5.04 or later).
2680
2681       Because the object IDs used with ":SECURE" mode are large random
2682       values, the :HASH_ONLY flag is forced on all the classes in the
2683       hierarchy.
2684
2685       For efficiency, it is recommended that the ":SECURE" flag be added to
2686       the topmost class(es) in a hierarchy.
2687

ATTRIBUTE HANDLERS

2689       Object::InsideOut uses attribute 'modify' handlers as described in
2690       "Package-specific Attribute Handling" in attributes, and provides a
2691       mechanism for adding attribute handlers to your own classes.  Instead
2692       of naming your attribute handler as "MODIFY_*_ATTRIBUTES", name it
2693       something else and then label it with the ":MODIFY_*_ATTRIBUTES"
2694       attribute (or ":MOD_*_ATTRS" for short).  Your handler should work just
2695       as described in "Package-specific Attribute Handling" in attributes
2696       with regard to its input arguments, and must return a list of the
2697       attributes which were not recognized by your handler.  Here's an
2698       example:
2699
2700        package My::Class; {
2701            use Object::InsideOut;
2702
2703            sub _scalar_attrs :MOD_SCALAR_ATTRS
2704            {
2705                my ($pkg, $scalar, @attrs) = @_;
2706                my @unused_attrs;         # List of any unhandled attributes
2707
2708                while (my $attr = shift(@attrs)) {
2709                    if ($attr =~ /.../) {
2710                        # Handle attribute
2711                        ...
2712                    } else {
2713                        # We don't handle this attribute
2714                        push(@unused_attrs, $attr);
2715                    }
2716                }
2717
2718                return (@unused_attrs);   # Pass along unhandled attributes
2719            }
2720        }
2721
2722       Attribute 'modify' handlers are called upward through the class
2723       hierarchy (i.e., bottom up).  This provides child classes with the
2724       capability to override the handling of attributes by parent classes, or
2725       to add attributes (via the returned list of unhandled attributes) for
2726       parent classes to process.
2727
2728       Attribute 'modify' handlers should be located at the beginning of a
2729       package, or at least before any use of attributes on the corresponding
2730       type of variable or subroutine:
2731
2732        package My::Class; {
2733            use Object::InsideOut;
2734
2735            sub _array_attrs :MOD_ARRAY_ATTRS
2736            {
2737               ...
2738            }
2739
2740            my @my_array :MyArrayAttr;
2741        }
2742
2743       For attribute 'fetch' handlers, follow the same procedures:  Label the
2744       subroutine with the ":FETCH_*_ATTRIBUTES" attribute (or
2745       ":FETCH_*_ATTRS" for short).  Contrary to the documentation in
2746       "Package-specific Attribute Handling" in attributes, attribute 'fetch'
2747       handlers receive two arguments: The relevant package name, and a
2748       reference to a variable or subroutine for which package-defined
2749       attributes are desired.
2750
2751       Attribute handlers are normal rendered hidden.
2752

SPECIAL USAGE

2754   Usage With "Exporter"
2755       It is possible to use Exporter to export functions from one inside-out
2756       object class to another:
2757
2758        use strict;
2759        use warnings;
2760
2761        package Foo; {
2762            use Object::InsideOut 'Exporter';
2763            BEGIN {
2764                our @EXPORT_OK = qw(foo_name);
2765            }
2766
2767            sub foo_name
2768            {
2769                return (__PACKAGE__);
2770            }
2771        }
2772
2773        package Bar; {
2774            use Object::InsideOut 'Foo' => [ qw(foo_name) ];
2775
2776            sub get_foo_name
2777            {
2778                return (foo_name());
2779            }
2780        }
2781
2782        package main;
2783
2784        print("Bar got Foo's name as '", Bar::get_foo_name(), "'\n");
2785
2786       Note that the "BEGIN" block is needed to ensure that the Exporter
2787       symbol arrays (in this case @EXPORT_OK) get populated properly.
2788
2789   Usage With "require" and "mod_perl"
2790       Object::InsideOut usage under mod_perl and with runtime-loaded classes
2791       is supported automatically; no special coding is required.
2792
2793       Caveat: Runtime loading of classes should be performed before any
2794       objects are created within any of the classes in their hierarchies.  If
2795       Object::InsideOut cannot create a hierarchy because of previously
2796       created objects (even if all those objects have been destroyed), a
2797       runtime error will be generated.
2798
2799   Singleton Classes
2800       A singleton class is a case where you would provide your own "->new()"
2801       method that in turn calls Object::InsideOut's "->new()" method:
2802
2803        package My::Class; {
2804            use Object::InsideOut;
2805
2806            my $singleton;
2807
2808            sub new {
2809                my $thing = shift;
2810                if (! $singleton) {
2811                    $singleton = $thing->Object::InsideOut::new(@_);
2812                }
2813                return ($singleton);
2814            }
2815        }
2816

DIAGNOSTICS

2818       Object::InsideOut uses "Exception::Class" for reporting errors.  The
2819       base error class for this module is "OIO".  Here is an example of the
2820       basic manner for trapping and handling errors:
2821
2822        my $obj;
2823        eval { $obj = My::Class->new(); };
2824        if (my $e = OIO->caught()) {
2825            warn('Failure creating object: '.$e);
2826            ...
2827        }
2828
2829       A more comprehensive approach might employ elements of the following:
2830
2831        eval { ... };
2832        if (my $e = OIO->caught()) {
2833            # An error generated by Object::InsideOut
2834            ...
2835        } elsif (my $e = Exception::Class::Base->caught()) {
2836            # An error generated by other code that uses Exception::Class
2837            ...
2838        } elsif ($@) {
2839            # An unhandled error (i.e., generated by code that doesn't use
2840            # Exception::Class)
2841            ...
2842        }
2843
2844       I have tried to make the messages and information returned by the error
2845       objects as informative as possible.  Suggested improvements are
2846       welcome.  Also, please bring to my attention any conditions that you
2847       encounter where an error occurs as a result of Object::InsideOut code
2848       that doesn't generate an Exception::Class object.  Here is one such
2849       error:
2850
2851       Invalid ARRAY/HASH attribute
2852           This error indicates you forgot "use Object::InsideOut;" in your
2853           class's code.
2854
2855       Object::InsideOut installs a "__DIE__" handler (see "die LIST" in
2856       perlfunc and "eval BLOCK" in perlfunc) to catch any errant exceptions
2857       from class-specific code, namely, ":Init", ":Replicate", ":Destroy",
2858       etc.  subroutines.  When using "eval" blocks inside these subroutines,
2859       you should localize $SIG{'__DIE__'} to keep Object::InsideOut's
2860       "__DIE__" handler from interfering with exceptions generated inside the
2861       "eval" blocks.  For example:
2862
2863        sub _init :Init {
2864            ...
2865            eval {
2866                local $SIG{'__DIE__'};
2867                ...
2868            };
2869            if $@ {
2870                # Handle caught exception
2871            }
2872            ...
2873        }
2874
2875       Here's another example, where the "die" function is used as a method of
2876       flow control for leaving an "eval" block:
2877
2878        eval {
2879            local $SIG{'__DIE__'};           # Suppress any existing __DIE__ handler
2880            ...
2881            die({'found' => 1}) if $found;   # Leave the eval block
2882            ...
2883        };
2884        if ($@) {
2885            die unless (ref($@) && $@->{'found'});   # Propagate any 'real' error
2886            # Handle 'found' case
2887            ...
2888        }
2889        # Handle 'not found' case
2890
2891       Similarly, if calling code from other modules that use the above flow
2892       control mechanism, but without localizing $SIG{'__DIE__'}, you can
2893       workaround this deficiency with your own "eval" block:
2894
2895        eval {
2896            local $SIG{'__DIE__'};     # Suppress any existing __DIE__ handler
2897            Some::Module::func();      # Call function that fails to localize
2898        };
2899        if ($@) {
2900            # Handle caught exception
2901        }
2902
2903       In addition, you should file a bug report against the offending module
2904       along with a patch that adds the missing "local $SIG{'__DIE__'};"
2905       statement.
2906

BUGS AND LIMITATIONS

2908       The equality operator (e.g., "if ($obj1 == $obj2) { ...") is overloaded
2909       for ":SHARED" classes when threads::shared is loaded.  The overload
2910       subroutine compares object classes and IDs because references to the
2911       same thread shared object may have different refaddrs.
2912
2913       You cannot overload an object to a scalar context (i.e., can't
2914       ":SCALARIFY").
2915
2916       You cannot use two instances of the same class with mixed thread object
2917       sharing in same application.
2918
2919       Cannot use attributes on subroutine stubs (i.e., forward declaration
2920       without later definition) with ":Automethod":
2921
2922        package My::Class; {
2923            sub method :Private;   # Will not work
2924
2925            sub _automethod :Automethod
2926            {
2927                # Code to handle call to 'method' stub
2928            }
2929        }
2930
2931       Due to limitations in the Perl parser, the entirety of any one
2932       attribute must be on a single line.  (However, multiple attributes may
2933       appear on separate lines.)
2934
2935       If a set accessor accepts scalars, then you can store any inside-out
2936       object type in it.  If its "Type" is set to "HASH", then it can store
2937       any blessed hash object.
2938
2939       Returning objects from threads does not work:
2940
2941        my $obj = threads->create(sub { return (Foo->new()); })->join();  # BAD
2942
2943       Instead, use thread object sharing, create the object before launching
2944       the thread, and then manipulate the object inside the thread:
2945
2946        my $obj = Foo->new();   # Class 'Foo' is set ':SHARED'
2947        threads->create(sub { $obj->set_data('bar'); })->join();
2948        my $data = $obj->get_data();
2949
2950       With Perl 5.8.8 and earlier, there are bugs associated with
2951       threads::shared that may prevent you from storing objects inside of
2952       shared objects, or using foreign inheritance with shared objects.  With
2953       Perl 5.8.9 (and later) together with threads::shared 1.15 (and later),
2954       you can store shared objects inside of other shared objects, and you
2955       can use foreign inheritance with shared objects (provided the foreign
2956       class supports shared objects as well).
2957
2958       Due to internal complexities, the following actions are not supported
2959       in code that uses threads::shared while there are any threads active:
2960
2961       ·   Runtime loading of Object::InsideOut classes
2962
2963       ·   Using ->add_class()
2964
2965       It is recommended that such activities, if needed, be performed in the
2966       main application code before any threads are created (or at least while
2967       there are no active threads).
2968
2969       For Perl 5.6.0 through 5.8.0, a Perl bug prevents package variables
2970       (e.g., object attribute arrays/hashes) from being referenced properly
2971       from subroutine refs returned by an ":Automethod" subroutine.  For Perl
2972       5.8.0 there is no workaround:  This bug causes Perl to core dump.  For
2973       Perl 5.6.0 through 5.6.2, the workaround is to create a ref to the
2974       required variable inside the ":Automethod" subroutine, and use that
2975       inside the subroutine ref:
2976
2977        package My::Class; {
2978            use Object::InsideOut;
2979
2980            my %data;
2981
2982            sub auto :Automethod
2983            {
2984                my $self = $_[0];
2985                my $name = $_;
2986
2987                my $data = \%data;      # Workaround for 5.6.X bug
2988
2989                return sub {
2990                            my $self = shift;
2991                            if (! @_) {
2992                                return ($$data{$name});
2993                            }
2994                            $$data{$name} = shift;
2995                       };
2996            }
2997        }
2998
2999       For Perl 5.8.1 through 5.8.4, a Perl bug produces spurious warning
3000       messages when threads are destroyed.  These messages are innocuous, and
3001       can be suppressed by adding the following to your application code:
3002
3003        $SIG{'__WARN__'} = sub {
3004                if ($_[0] !~ /^Attempt to free unreferenced scalar/) {
3005                    print(STDERR @_);
3006                }
3007            };
3008
3009       A better solution would be to upgrade threads and threads::shared from
3010       CPAN, especially if you encounter other problems associated with
3011       threads.
3012
3013       For Perl 5.8.4 and 5.8.5, the "Storable" feature does not work due to a
3014       Perl bug.  Use Object::InsideOut v1.33 if needed.
3015
3016       Due to bugs in the Perl interpreter, using the introspection API (i.e.
3017       "->meta()", etc.) requires Perl 5.8.0 or later.
3018
3019       The version of Want that is available via PPM for ActivePerl is
3020       defective, and causes failures when using ":lvalue" accessors.  Remove
3021       it, and then download and install the Want module using CPAN.
3022
3023       Devel::StackTrace (used by Exception::Class) makes use of the DB
3024       namespace.  As a consequence, Object::InsideOut thinks that
3025       "package DB" is already loaded.  Therefore, if you create a class
3026       called DB that is sub-classed by other packages, you may need to
3027       "require" it as follows:
3028
3029        package DB::Sub; {
3030            require DB;
3031            use Object::InsideOut qw(DB);
3032            ...
3033        }
3034
3035       View existing bug reports at, and submit any new bugs, problems,
3036       patches, etc.  to:
3037       http://rt.cpan.org/Public/Dist/Display.html?Name=Object-InsideOut
3038       <http://rt.cpan.org/Public/Dist/Display.html?Name=Object-InsideOut>
3039

REQUIREMENTS

3041       Perl 5.6.0 or later
3042       Exception::Class v1.22 or later
3043       Scalar::Util v1.10 or later
3044           It is possible to install a pure perl version of Scalar::Util,
3045           however, it will be missing the weaken() function which is needed
3046           by Object::InsideOut.  You'll need to upgrade your version of
3047           Scalar::Util to one that supports its "XS" code.
3048
3049       Test::More v0.50 or later
3050           Needed for testing during installation.
3051
3052       Want v0.12 or later
3053           Optional.  Provides support for ":lvalue Accessors".
3054
3055       Math::Random::MT::Auto v5.04 or later)
3056           Optional.  Provides support for :SECURE mode.
3057
3058       To cover all of the above requirements and more, it is recommended that
3059       you install Bundle::Object::InsideOut using CPAN:
3060
3061        perl -MCPAN -e 'install Bundle::Object::InsideOut'
3062
3063       This will install the latest versions of all the required and optional
3064       modules needed for full support of all of the features provided by
3065       Object::InsideOut.
3066

SEE ALSO

3068       Object::InsideOut Discussion Forum on CPAN:
3069       http://www.cpanforum.com/dist/Object-InsideOut
3070       <http://www.cpanforum.com/dist/Object-InsideOut>
3071
3072       Annotated POD for Object::InsideOut:
3073       http://annocpan.org/~JDHEDDEN/Object-InsideOut-3.56/lib/Object/InsideOut.pm
3074       <http://annocpan.org/~JDHEDDEN/Object-
3075       InsideOut-3.56/lib/Object/InsideOut.pm>
3076
3077       Source repository: http://code.google.com/p/object-insideout/
3078       <http://code.google.com/p/object-insideout/>
3079
3080       Inside-out Object Model:
3081       <http://www.perlfoundation.org/perl5/index.cgi?inside_out_object>,
3082       <http://www.perlmonks.org/?node_id=219378>,
3083       <http://www.perlmonks.org/?node_id=483162>,
3084       <http://www.perlmonks.org/?node_id=515650>, Chapters 15 and 16 of Perl
3085       Best Practices by Damian Conway
3086
3087       Object::InsideOut::Metadata
3088
3089       Storable, <Exception:Class>, Want, Math::Random::MT::Auto, attributes,
3090       overload
3091

ACKNOWLEDGEMENTS

3093       Abigail <perl AT abigail DOT nl> for inside-out objects in general.
3094
3095       Damian Conway <dconway AT cpan DOT org> for Class::Std.
3096
3097       David A. Golden <dagolden AT cpan DOT org> for thread handling for
3098       inside-out objects.
3099
3100       Dan Kubb <dan.kubb-cpan AT autopilotmarketing DOT com> for ":Chained"
3101       methods.
3102

AUTHOR

3104       Jerry D. Hedden, <jdhedden AT cpan DOT org>
3105
3107       Copyright 2005 - 2009 Jerry D. Hedden. All rights reserved.
3108
3109       This program is free software; you can redistribute it and/or modify it
3110       under the same terms as Perl itself.
3111

TRANSLATIONS

3113       A Japanese translation of this documentation by TSUJII, Naofumi
3114       <tsun DOT nt AT gmail DOT com> is available at
3115       <http://perldoc.jp/docs/modules/>.
3116
3117
3118
3119perl v5.12.0                      2009-07-29              Object::InsideOut(3)
Impressum