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 4.05
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       ·   Exception Objects
161
162           Object::InsideOut uses Exception::Class for handling errors in an
163           OO-compatible manner.
164
165       ·   Object Serialization
166
167           Object::InsideOut has built-in support for object dumping and
168           reloading that can be accomplished in either an automated fashion
169           or through the use of class-supplied subroutines.  Serialization
170           using Storable is also supported.
171
172       ·   Foreign Class Inheritance
173
174           Object::InsideOut allows classes to inherit from foreign (i.e.,
175           non-Object::InsideOut) classes, thus allowing you to sub-class
176           other Perl class, and access their methods from your own objects.
177
178       ·   Introspection
179
180           Obtain constructor parameters and method metadata for
181           Object::InsideOut classes.
182

CLASSES

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

OBJECTS

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

ATTRIBUTES

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

FIELDS

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

OBJECT INITIALIZATION

444       As stated in "Object Creation", object fields are initially populated
445       with data as part of the object creation process by passing
446       "key => value" parameters to the "->new()" method.  These parameters
447       can be processed automatically into object fields, or can be passed to
448       a class-specific object initialization subroutine.
449
450   Field-Specific Parameters
451       When an object creation parameter corresponds directly to an object
452       field, you can specify for Object::InsideOut to automatically place the
453       parameter into the field by adding the ":Arg" attribute to the field
454       declaration:
455
456        my @foo :Field :Arg(foo);
457
458       For the above, the following would result in $val being placed in
459       "My::Class"'s @foo field during object creation:
460
461        my $obj = My::Class->new('foo' => $val);
462
463   Object Initialization Subroutines
464       Many times, object initialization parameters do not correspond directly
465       to object fields, or they may require special handling.  For these,
466       parameter processing is accomplished through a combination of an
467       ":InitArgs" labeled hash, and an ":Init" labeled subroutine.
468
469       The ":InitArgs" labeled hash specifies the parameters to be extracted
470       from the argument list supplied to the "->new()" method.  Those
471       parameters (and only those parameters) which match the keys in the
472       ":InitArgs" hash are then packaged together into a single hash ref.
473       The newly created object and this parameter hash ref are then sent to
474       the ":Init" subroutine for processing.
475
476       Here is an example of a class with an automatically handled field and
477       an :Init handled field:
478
479        package My::Class; {
480            use Object::InsideOut;
481
482            # Automatically handled field
483            my @my_data  :Field  :Acc(data)  :Arg(MY_DATA);
484
485            # ':Init' handled field
486            my @my_field :Field;
487
488            my %init_args :InitArgs = (
489                'MY_PARAM' => '',
490            );
491
492            sub _init :Init
493            {
494                my ($self, $args) = @_;
495
496                if (exists($args->{'MY_PARAM'})) {
497                    $self->set(\@my_field, $args->{'MY_PARAM'});
498                }
499            }
500
501            ...
502        }
503
504       An object for this class would be created as follows:
505
506        my $obj = My::Class->new('MY_DATA'  => $dat,
507                                 'MY_PARAM' => $parm);
508
509       This results in, first of all, $dat being placed in the object's
510       @my_data field because the "MY_DATA" key is specified in the ":Arg"
511       attribute for that field.
512
513       Then, "_init" is invoked with arguments consisting of the object (i.e.,
514       $self) and a hash ref consisting only of "{ 'MY_PARAM' => $param }"
515       because the key "MY_PARAM" is specified in the ":InitArgs" hash.
516       "_init" checks that the parameter "MY_PARAM" exists in the hash ref,
517       and then (since it does exist) adds $parm to the object's @my_field
518       field.
519
520       Setting Data
521           Data processed by the ":Init" subroutine may be placed directly
522           into the class's field arrays (hashes) using the object's ID (i.e.,
523           $$self):
524
525            $my_field[$$self] = $args->{'MY_PARAM'};
526
527           However, as shown in the example above, it is strongly recommended
528           that you use the ->set() method:
529
530            $self->set(\@my_field, $args->{'MY_PARAM'});
531
532           which handles converting the data to a shared format when needed
533           for applications using threads::shared.
534
535       All Parameters
536           The ":InitArgs" hash and the ":Arg" attribute on fields act as
537           filters that constrain which initialization parameters are and are
538           not sent to the ":Init" subroutine.  If, however, a class does not
539           have an ":InitArgs" hash and does not use the ":Arg" attribute on
540           any of its fields, then its ":Init" subroutine (if it exists, of
541           course) will get all the initialization parameters supplied to the
542           "->new()" method.
543
544   Mandatory Parameters
545       Field-specific parameters may be declared mandatory as follows:
546
547        my @data :Field
548                 :Arg('Name' => 'data', 'Mandatory' => 1);
549
550       If a mandatory parameter is missing from the argument list to
551       "->new()", an error is generated.
552
553       For ":Init" handled parameters, use:
554
555        my %init_args :InitArgs = (
556            'data' => {
557                'Mandatory' => 1,
558            },
559        );
560
561       "Mandatory" may be abbreviated to "Mand", and "Required" or "Req" are
562       synonymous.
563
564   Default Values
565       For optional parameters, defaults can be specified for field-specific
566       parameters using either of these syntaxes:
567
568        my @data :Field
569                 :Arg('Name' => 'data', 'Default' => 'foo');
570
571        my @info :Field  :Arg(info)  :Default('bar');
572
573       If an optional parameter with a specified default is missing from the
574       argument list to "->new()", then the default is assigned to the field
575       when the object is created (before the ":Init" subroutine, if any, is
576       called).
577
578       The format for ":Init" handled parameters is:
579
580        my %init_args :InitArgs = (
581            'data' => {
582                'Default' => 'foo',
583            },
584        );
585
586       In this case, if the parameter is missing from the argument list to
587       "->new()", then the parameter key is paired with the default value and
588       added to the ":Init" argument hash ref (e.g., "{ 'data' => 'foo' }").
589
590       Fields can also be assigned a default value even if not associated with
591       an initialization parameter:
592
593        my @hash  :Field  :Default({});
594        my @tuple :Field  :Default([1, 'bar']);
595
596       Note that when using ":Default", the value must be properly structured
597       Perl code (e.g., strings must be quoted as illustrated above).
598
599       "Default" and ":Default" may be abbreviated to "Def" and ":Def"
600       respectively.
601
602       Generated Default Values
603
604       It is also possible to generate default values on a per object basis by
605       using code in the ":Default" directive.
606
607        my @IQ :Field  :Default(50 + rand 100);
608        my @ID :Field  :Default(our $next; ++$next);
609
610       The above, for example, will initialize the "IQ" attribute of each new
611       object to a different random number, while its "ID" attribute will be
612       initialized with a sequential integer.
613
614       The code in a ":Default" specifier can also refer to the object being
615       initialized, either as $_[0] or as $self.  For example:
616
617        my @unique_ID :Field  :Default($self->gen_unique_ID);
618
619       Any code specified as a default will not have access to the surrounding
620       lexical scope.  For example, this will not work:
621
622        my $MAX = 100;
623        my $MIN = 0;
624
625        my @bar :Field
626                :Default($MIN + rand($MAX-$MIX));     # Error
627
628       For anything lexical or complex, you should factor the initializer out
629       into a utility subroutine:
630
631        sub _rand_max :Restricted
632        {
633            $MIN + rand($MAX-$MIX)
634        }
635
636        my @bar :Field
637                :Default(_rand_max);
638
639       When specifying a generated default using the "Default" tag inside an
640       ":Arg" directive, you will need to wrap the code in a "sub { }", and
641       $_[0] (but not $self) can be used to access the object being
642       initialized:
643
644        my @baz :Field
645                :Arg(Name => 'baz', Default => sub { $_[0]->biz });
646
647       System functions need to similarly be wrapped in "sub { }":
648
649        my @rand :Field
650                 :Type(numeric)
651                 :Arg(Name => 'Rand', Default => sub { rand });
652
653       Subroutines can be accessed using a code reference:
654
655        my @data :Field
656                 :Arg(Name => 'Data', Default => \&gen_default);
657
658       On the other hand, the above can also be simplified by using the
659       ":Default" directive instead:
660
661        my @baz  :Field  :Arg(baz)   :Default($self->biz);
662        my @rand :Field  :Arg(Rand)  :Default(rand)  :Type(numeric);
663        my @data :Field  :Arg(Data)  :Default(gen_default);
664
665       Using generated defaults in the ":InitArgs" hash requires the use of
666       the same types of syntax as with the "Default" tag in an ":Arg"
667       directive:
668
669        my %init_args :InitArgs = (
670            'Baz' => {
671                'Default' => sub { $_[0]->biz },
672            },
673            'Rand' => {
674                'Default' => sub { rand },
675            },
676            'Data' => {
677                'Default' => \&gen_default,
678            },
679        );
680
681       Sequential defaults
682
683       In the previous section, one of the examples is not as safe or as
684       convenient as it should be:
685
686        my @ID :Field  :Default(our $next; ++$next);
687
688       The problem is the shared variable ($next) that's needed to track the
689       allocation of "ID" values.  Because it has to persist between calls,
690       that variable has to be a package variable, except under Perl 5.10 or
691       later where it could be a state variable instead:
692
693        use feature 'state';
694
695        my @ID :Field  :Default(state $next; ++$next);
696
697       The version with the package variable is unsafe, because anyone could
698       then spoof ID numbers just by reassigning that universally accessible
699       variable:
700
701           $MyClass::next = 0;        # Spoof the next object
702           my $obj = MyClass->new;    # Object now has ID 1
703
704       The state-variable version avoids this problem, but even that version
705       is more complicated (and hence more error-prone) than it needs to be.
706
707       The ":SequenceFrom" directive (which can be abbreviated to ":SeqFrom"
708       or ":Seq") makes it much easier to specify that an attribute's default
709       value is taken from a linearly increasing sequence.  For instance, the
710       ID example above could be rewritten as:
711
712        my @ID :Field  :SequenceFrom(1);
713
714       This directive automatically creates a hidden variable, initializes it
715       to the initial value specified, generates a sequence starting at that
716       initial value, and then uses successive elements of that sequence each
717       time a default value is needed for that attribute during object
718       creation.
719
720       If the initial value is a scalar, then the default sequence is
721       generated by by computing "$previous_value++".  If it is an object, it
722       is generated by calling "$obj->next()" (or by calling "$obj++" if the
723       object doesn't have a "next()" method).
724
725       This makes it simple to create a series of objects with attributes
726       whose values default to simple numeric, alphabetic, or alphanumeric
727       sequences, or to the sequence specified by an iterator object of some
728       kind:
729
730        my @ID :Field  :SeqFrom(1);                 # 1, 2, 3...
731
732        my @ID :Field  :SeqFrom('AAA');             # 'AAA', 'AAB', 'AAC'...
733
734        my @ID :Field  :SeqFrom('A01');             # 'A01', 'A02', 'A03'...
735
736        my @ID :Field  :SeqFrom(ID_Iterator->new);  # ->next, ->next, ->next...
737
738       In every other respect a ":SequenceFrom" directive is just like a
739       ":Default".  For example, it can be used in conjunction with the ":Arg"
740       directive as follows:
741
742        my @ID :Field  :Arg(ID)  :SeqFrom(1);
743
744       However, not as a tag inside the ":Arg" directive:
745
746        my @ID :Field  :Arg('Name' => 'ID', 'SeqFrom' => 1)   # WRONG
747
748       For the ":InitArgs" hash, you will need to roll your own sequential
749       defaults if required:
750
751        use feature 'state';
752
753        my %init_args :InitArgs = (
754            'Counter' => {
755                'Default' => sub { state $next; ++$next }
756            },
757        );
758
759   Parameter Name Matching
760       Rather than having to rely on exact matches to parameter keys in the
761       "->new()" argument list, you can specify a regular expressions to be
762       used to match them to field-specific parameters:
763
764        my @param :Field
765                  :Arg('Name' => 'param', 'Regexp' => qr/^PARA?M$/i);
766
767       In this case, the parameter's key could be any of the following: PARAM,
768       PARM, Param, Parm, param, parm, and so on.  And the following would
769       result in $data being placed in "My::Class"'s @param field during
770       object creation:
771
772        my $obj = My::Class->new('Parm' => $data);
773
774       For ":Init" handled parameters, you would similarly use:
775
776        my %init_args :InitArgs = (
777            'Param' => {
778                'Regex' => qr/^PARA?M$/i,
779            },
780        );
781
782       In this case, the match results in "{ 'Param' => $data }" being sent to
783       the ":Init" subroutine as the argument hash.  Note that the ":InitArgs"
784       hash key is substituted for the original argument key.  This eliminates
785       the need for any parameter key pattern matching within the ":Init"
786       subroutine.
787
788       "Regexp" may be abbreviated to "Regex" or "Re".
789
790   Object Pre-initialization
791       Occasionally, a child class may need to send a parameter to a parent
792       class as part of object initialization.  This can be accomplished by
793       supplying a ":PreInit" labeled subroutine in the child class.  These
794       subroutines, if found, are called in order from the bottom of the class
795       hierarchy upward (i.e., child classes first).
796
797       The subroutine should expect two arguments:  The newly created
798       (uninitialized) object (i.e., $self), and a hash ref of all the
799       parameters from the "->new()" method call, including any additional
800       parameters added by other ":PreInit" subroutines.
801
802        sub pre_init :PreInit
803        {
804            my ($self, $args) = @_;
805            ...
806        }
807
808       The parameter hash ref will not be exactly as supplied to "->new()",
809       but will be flattened into a single hash ref.  For example,
810
811        my $obj = My::Class->new(
812            'param_X' => 'value_X',
813            {
814                'param_A' => 'value_A',
815                'param_B' => 'value_B',
816            },
817            'My::Class' => { 'param' => 'value' },
818        );
819
820       would produce
821
822        {
823            'param_X' => 'value_X',
824            'param_A' => 'value_A',
825            'param_B' => 'value_B',
826            'My::Class' => { 'param' => 'value' }
827        }
828
829       as the hash ref to the ":PreInit" subroutine.
830
831       The ":PreInit" subroutine may then add, modify or even remove any
832       parameters from the hash ref as needed for its purposes.  After all the
833       ":PreInit" subroutines have been executed, object initialization will
834       then proceed using the resulting parameter hash.
835
836       The ":PreInit" subroutine should not try to set data in its class's
837       fields or in other class's fields (e.g., using set methods) as such
838       changes will be overwritten during initialization phase which follows
839       pre-initialization.  The ":PreInit" subroutine is only intended for
840       modifying initialization parameters prior to initialization.
841
842   Initialization Sequence
843       For the most part, object initialization can be conceptualized as
844       proceeding from parent classes down through child classes.  As such,
845       calling child class methods from a parent class during object
846       initialization may not work because the object will not have been fully
847       initialized in the child classes.
848
849       Knowing the order of events during object initialization may help in
850       determining when this can be done safely:
851
852       1.  The scalar reference for the object is created, populated with an
853       "Object ID", and blessed into the appropriate class.
854       2.  :PreInit subroutines are called in order from the bottom of the
855       class hierarchy upward (i.e., child classes first).
856       3.  From the top of the class hierarchy downward (i.e., parent classes
857       first), "Default Values" are assigned to fields.  (These may be
858       overwritten by subsequent steps below.)
859       4.  From the top of the class hierarchy downward, parameters to the
860       "->new()" method are processed for ":Arg" field attributes and entries
861       in the ":InitArgs" hash:
862           a.  "Parameter Preprocessing" is performed.
863           b.  Checks for "Mandatory Parameters" are made.
864           c.  "Default Values" specified in the ":InitArgs" hash are added
865           for subsequent processing by the ":Init" subroutine.
866           d.  Type checking is performed.
867           e.  "Field-Specific Parameters" are assigned to fields.
868       5.  From the top of the class hierarchy downward, :Init subroutines are
869       called with parameters specified in the ":InitArgs" hash.
870       6.  Checks are made for any parameters to "->new()" that were not
871       handled in the above.  (See next section.)
872
873   Unhandled Parameters
874       It is an error to include any parameters to the "->new()" method that
875       are not handled by at least one class in the hierarchy.  The primary
876       purpose of this is to catch typos in parameter names:
877
878         my $obj = Person->new('nane' => 'John');   # Should be 'name'
879
880       The only time that checks for unhandled parameters are not made is when
881       at least one class in the hierarchy does not have an ":InitArgs" hash
882       and does not use the ":Arg" attribute on any of its fields and uses an
883       :Init subroutine for processing parameters.  In such a case, it is not
884       possible for Object::InsideOut to determine which if any of the
885       parameters are not handled by the ":Init" subroutine.
886
887       If you add the following construct to the start of your application:
888
889        BEGIN {
890            no warnings 'once';
891            $OIO::Args::Unhandled::WARN_ONLY = 1;
892        }
893
894       then unhandled parameters will only generate warnings rather than
895       causing exceptions to be thrown.
896
897   Modifying ":InitArgs"
898       For performance purposes, Object::InsideOut normalizes each class's
899       ":InitArgs" hash by creating keys in the form of '_X' for the various
900       options it handles (e.g., '_R' for 'Regexp').
901
902       If a class has the unusual requirement to modify its ":InitArgs" hash
903       during runtime, then it must renormalize the hash after making such
904       changes by invoking "Object::InsideOut::normalize()" on it so that
905       Object::InsideOut will pick up the changes:
906
907        Object::InsideOut::normalize(\%init_args);
908

ACCESSOR GENERATION

910       Accessors are object methods used to get data out of and put data into
911       an object.  You can, of course, write your own accessor code, but this
912       can get a bit tedious, especially if your class has lots of fields.
913       Object::InsideOut provides the capability to automatically generate
914       accessors for you.
915
916   Basic Accessors
917       A get accessor is vary basic:  It just returns the value of an object's
918       field:
919
920        my @data :Field;
921
922        sub fetch_data
923        {
924            my $self = shift;
925            return ($data[$$self]);
926        }
927
928       and you would use it as follows:
929
930        my $data = $obj->fetch_data();
931
932       To have Object::InsideOut generate such a get accessor for you, add a
933       ":Get" attribute to the field declaration, specifying the name for the
934       accessor in parentheses:
935
936        my @data :Field :Get(fetch_data);
937
938       Similarly, a set accessor puts data in an object's field.  The set
939       accessors generated by Object::InsideOut check that they are called
940       with at least one argument.  They are specified using the ":Set"
941       attribute:
942
943        my @data :Field :Set(store_data);
944
945       Some programmers use the convention of naming get and set accessors
946       using get_ and set_ prefixes.  Such standard accessors can be generated
947       using the ":Standard" attribute (which may be abbreviated to ":Std"):
948
949        my @data :Field :Std(data);
950
951       which is equivalent to:
952
953        my @data :Field :Get(get_data) :Set(set_data);
954
955       Other programmers prefer to use a single combination accessors that
956       performs both functions:  When called with no arguments, it gets, and
957       when called with an argument, it sets.  Object::InsideOut will generate
958       such accessors with the ":Accessor" attribute.  (This can be
959       abbreviated to ":Acc", or you can use ":Get_Set" or ":Combined" or
960       ":Combo" or even "Mutator".)  For example:
961
962        my @data :Field :Acc(data);
963
964       The generated accessor would be used in this manner:
965
966        $obj->data($val);           # Puts data into the object's field
967        my $data = $obj->data();    # Fetches the object's field data
968
969   Set Accessor Return Value
970       For any of the automatically generated methods that perform set
971       operations, the default for the method's return value is the value
972       being set (i.e., the new value).
973
974       You can specify the set accessor's return value using the "Return"
975       attribute parameter (which may be abbreviated to "Ret").  For example,
976       to explicitly specify the default behavior use:
977
978        my @data :Field :Set('Name' => 'store_data', 'Return' => 'New');
979
980       You can specify that the accessor should return the old (previous)
981       value (or "undef" if unset):
982
983        my @data :Field :Acc('Name' => 'data', 'Ret' => 'Old');
984
985       You may use "Previous", "Prev" or "Prior" as synonyms for "Old".
986
987       Finally, you can specify that the accessor should return the object
988       itself:
989
990        my @data :Field :Std('Name' => 'data', 'Ret' => 'Object');
991
992       "Object" may be abbreviated to "Obj", and is also synonymous with
993       "Self".
994
995   Method Chaining
996       An obvious case where method chaining can be used is when a field is
997       used to store an object:  A method for the stored object can be chained
998       to the get accessor call that retrieves that object:
999
1000        $obj->get_stored_object()->stored_object_method()
1001
1002       Chaining can be done off of set accessors based on their return value
1003       (see above).  In this example with a set accessor that returns the new
1004       value:
1005
1006        $obj->set_stored_object($stored_obj)->stored_object_method()
1007
1008       the set_stored_object() call stores the new object, returning it as
1009       well, and then the stored_object_method() call is invoked via the
1010       stored/returned object.  The same would work for set accessors that
1011       return the old value, too, but in that case the chained method is
1012       invoked via the previously stored (and now returned) object.
1013
1014       If the Want module (version 0.12 or later) is available, then
1015       Object::InsideOut also tries to do the right thing with method chaining
1016       for set accessors that don't store/return objects.  In this case, the
1017       object used to invoke the set accessor will also be used to invoke the
1018       chained method (just as though the set accessor were declared with
1019       'Return' => 'Object'):
1020
1021        $obj->set_data('data')->do_something();
1022
1023       To make use of this feature, just add "use Want;" to the beginning of
1024       your application.
1025
1026       Note, however, that this special handling does not apply to get
1027       accessors, nor to combination accessors invoked without an argument
1028       (i.e., when used as a get accessor).  These must return objects in
1029       order for method chaining to succeed.
1030
1031   :lvalue Accessors
1032       As documented in "Lvalue subroutines" in perlsub, an ":lvalue"
1033       subroutine returns a modifiable value.  This modifiable value can then,
1034       for example, be used on the left-hand side (hence "LVALUE") of an
1035       assignment statement, or a substitution regular expression.
1036
1037       For Perl 5.8.0 and later, Object::InsideOut supports the generation of
1038       ":lvalue" accessors such that their use in an "LVALUE" context will set
1039       the value of the object's field.  Just add "'lvalue' => 1" to the set
1040       accessor's attribute.  ('lvalue' may be abbreviated to 'lv'.)
1041
1042       Additionally, ":Lvalue" (or its abbreviation ":lv") may be used for a
1043       combined get/set :lvalue accessor.  In other words, the following are
1044       equivalent:
1045
1046        :Acc('Name' => 'email', 'lvalue' => 1)
1047
1048        :Lvalue(email)
1049
1050       Here is a detailed example:
1051
1052        package Contact; {
1053            use Object::InsideOut;
1054
1055            # Create separate a get accessor and an :lvalue set accessor
1056            my @name  :Field
1057                      :Get(name)
1058                      :Set('Name' => 'set_name', 'lvalue' => 1);
1059
1060            # Create a standard get_/set_ pair of accessors
1061            #   The set_ accessor will be an :lvalue accessor
1062            my @phone :Field
1063                      :Std('Name' => 'phone', 'lvalue' => 1);
1064
1065            # Create a combined get/set :lvalue accessor
1066            my @email :Field
1067                      :Lvalue(email);
1068        }
1069
1070        package main;
1071
1072        my $obj = Contact->new();
1073
1074        # Use :lvalue accessors in assignment statements
1075        $obj->set_name()  = 'Jerry D. Hedden';
1076        $obj->set_phone() = '800-555-1212';
1077        $obj->email()     = 'jdhedden AT cpan DOT org';
1078
1079        # Use :lvalue accessor in substitution regexp
1080        $obj->email() =~ s/ AT (\w+) DOT /\@$1./;
1081
1082        # Use :lvalue accessor in a 'substr' call
1083        substr($obj->set_phone(), 0, 3) = '888';
1084
1085        print("Contact info:\n");
1086        print("\tName:  ", $obj->name(),      "\n");
1087        print("\tPhone: ", $obj->get_phone(), "\n");
1088        print("\tEmail: ", $obj->email(),     "\n");
1089
1090       The use of ":lvalue" accessors requires the installation of the Want
1091       module (version 0.12 or later) from CPAN.  See particularly the section
1092       "Lvalue subroutines:" in Want for more information.
1093
1094       ":lvalue" accessors also work like regular set accessors in being able
1095       to accept arguments, return values, and so on:
1096
1097        my @pri :Field
1098                :Lvalue('Name' => 'priority', 'Return' => 'Old');
1099         ...
1100        my $old_pri = $obj->priority(10);
1101
1102       ":lvalue" accessors can be used in method chains.
1103
1104       Caveats: While still classified as experimental, Perl's support for
1105       ":lvalue" subroutines has been around since 5.6.0, and a good number of
1106       CPAN modules make use of them.
1107
1108       By definition, because ":lvalue" accessors return the location of a
1109       field, they break encapsulation.  As a result, some OO advocates eschew
1110       the use of ":lvalue" accessors.
1111
1112       ":lvalue" accessors are slower than corresponding non-lvalue accessors.
1113       This is due to the fact that more code is needed to handle all the
1114       diverse ways in which ":lvalue" accessors may be used.  (I've done my
1115       best to optimize the generated code.)  For example, here's the code
1116       that is generated for a simple combined accessor:
1117
1118        *Foo::foo = sub {
1119            return ($$field[${$_[0]}]) if (@_ == 1);
1120            $$field[${$_[0]}] = $_[1];
1121        };
1122
1123       And the corresponding code for an ":lvalue" combined accessor:
1124
1125        *Foo::foo = sub :lvalue {
1126            my $rv = !Want::want_lvalue(0);
1127            Want::rreturn($$field[${$_[0]}]) if ($rv && (@_ == 1));
1128            my $assign;
1129            if (my @args = Want::wantassign(1)) {
1130                @_ = ($_[0], @args);
1131                $assign = 1;
1132            }
1133            if (@_ > 1) {
1134                $$field[${$_[0]}] = $_[1];
1135                Want::lnoreturn if $assign;
1136                Want::rreturn($$field[${$_[0]}]) if $rv;
1137            }
1138            ((@_ > 1) && (Want::wantref() eq 'OBJECT') &&
1139             !Scalar::Util::blessed($$field[${$_[0]}]))
1140                   ? $_[0] : $$field[${$_[0]}];
1141        };
1142

ALL-IN-ONE

1144       Parameter naming and accessor generation may be combined:
1145
1146        my @data :Field :All(data);
1147
1148       This is syntactic shorthand for:
1149
1150        my @data :Field :Arg(data) :Acc(data);
1151
1152       If you want the accessor to be ":lvalue", use:
1153
1154        my @data :Field :LV_All(data);
1155
1156       If standard accessors are desired, use:
1157
1158        my @data :Field :Std_All(data);
1159
1160       Attribute parameters affecting the set accessor may also be used.  For
1161       example, if you want standard accessors with an ":lvalue" set accessor:
1162
1163        my @data :Field :Std_All('Name' => 'data', 'Lvalue' => 1);
1164
1165       If you want a combined accessor that returns the old value on set
1166       operations:
1167
1168        my @data :Field :All('Name' => 'data', 'Ret' => 'Old');
1169
1170       And so on.
1171
1172       If you need to add attribute parameters that affect the ":Arg" portion
1173       (e.g., "Default", "Mandatory", etc.), then you cannot use ":All".  Fall
1174       back to using the separate attributes.  For example:
1175
1176        my @data :Field :Arg('Name' => 'data', 'Mand' => 1)
1177                        :Acc('Name' => 'data', 'Ret' => 'Old');
1178

READONLY FIELDS

1180       If you want to declare a read-only field (i.e., one that can be
1181       initialized and retrieved, but which doesn't have a set accessor):
1182
1183        my @data :Field :Arg(data) :Get(data);
1184
1185       there is a syntactic shorthand for that, too:
1186
1187        my @data :Field :ReadOnly(data);
1188
1189       or just:
1190
1191        my @data :Field :RO(data);
1192
1193       If a standard get accessor is desired, use:
1194
1195        my @data :Field :Std_RO(data);
1196
1197       For obvious reasons, attribute parameters affecting the set accessor
1198       cannot be used with read-only fields, nor can ":ReadOnly" be combined
1199       with ":LValue".
1200
1201       As with ":All", if you need to add attribute parameters that affect the
1202       ":Arg" portion then you cannot use the ":RO" shorthand:  Fall back to
1203       using the separate attributes in such cases.  For example:
1204
1205        my @data :Field :Arg('Name' => 'data', 'Mand' => 1)
1206                        :Get('Name' => 'data');
1207

DELEGATORS

1209       In addition to autogenerating accessors for a given field, you can also
1210       autogenerate delegators to that field.  A delegator is an accessor that
1211       forwards its call to one of the object's fields.
1212
1213       For example, if your Car object has an @engine field, then you might
1214       need to send all acceleration requests to the Engine object stored in
1215       that field.  Likewise, all braking requests may need to be forwarded to
1216       Car's field that stores the Brakes object:
1217
1218        package Car; {
1219            use Object::InsideOut;
1220
1221            my @engine :Field :Get(engine);
1222            my @brakes :Field :Get(brakes);
1223
1224            sub _init :Init(private)  {
1225                my ($self, $args) = @_;
1226
1227                $self->engine(Engine->new());
1228                $self->brakes(Brakes->new());
1229            }
1230
1231            sub accelerate {
1232                my ($self) = @_;
1233                $self->engine->accelerate();
1234            }
1235
1236            sub decelerate {
1237                my ($self) = @_;
1238                $self->engine->decelerate();
1239            }
1240
1241            sub brake {
1242                my ($self, $foot_pressure) = @_;
1243                $self->brakes->brake($foot_pressure);
1244            }
1245        }
1246
1247       If the Car needs to forward other method calls to its Engine or Brakes,
1248       this quickly becomes tedious, repetitive, and error-prone. So, instead,
1249       you can just tell Object::InsideOut that a particular method should be
1250       automatically forwarded to a particular field, by specifying a
1251       ":Handles" attribute:
1252
1253        package Car; {
1254            use Object::InsideOut;
1255
1256            my @engine :Field
1257                       :Get(engine)
1258                       :Handles(accelerate, decelerate);
1259            my @brakes :Field
1260                       :Get(brakes)
1261                       :Handles(brake);
1262
1263            sub _init :Init(private)  {
1264                my ($self, $args) = @_;
1265
1266                $self->engine(Engine->new());
1267                $self->brakes(Brakes->new());
1268            }
1269        }
1270
1271       This option generates and installs a single delegator method for each
1272       of its arguments, so the second example has exactly the same effect as
1273       the first example. The delegator simply calls the corresponding method
1274       on the object stored in the field, passing it the same argument list it
1275       received.
1276
1277       Sometimes, however, you may need to delegate a particular method to a
1278       field, but under a different name.  For example, if the Brake class
1279       provides an "engage()" method, rather than a "brake()" method, then
1280       you'd need "Car::brake()" to be implemented as:
1281
1282            sub brake {
1283                my ($self, $foot_pressure) = @_;
1284                $self->brakes->engage($foot_pressure);
1285            }
1286
1287       You can achieve that using the ":Handles" attribute, like so:
1288
1289            my @brakes :Field
1290                       :Get(brakes)
1291                       :Handles(brake-->engage);
1292
1293       The long arrow version still creates a delegator method "brake()", but
1294       makes that method delegate to your Brakes object by calling its
1295       "engage()" method instead.
1296
1297       If you are delegating a large number of methods to a particular field,
1298       the ":Handles" declarations soon become tedious:
1299
1300        my @onboard_computer :Field :Get(comp)
1301                             :Type(Computer::Onboard)
1302                             :Handles(engine_monitor engine_diagnostics)
1303                             :Handles(engine_control airbag_deploy)
1304                             :Handles(GPS_control GPS_diagnostics GPS_reset)
1305                             :Handles(climate_control reversing_camera)
1306                             :Handles(cruise_control auto_park)
1307                             :Handles(iPod_control cell_phone_connect);
1308
1309       And, of course, every time the interface of the "Computer::Onboard"
1310       class changes, you have to change those ":Handles" declarations, too.
1311
1312       Sometimes, all you really want to say is: "This field should handle
1313       anything it can handle".  To do that, you write:
1314
1315        my @onboard_computer :Field :Get(comp)
1316                             :Type(Computer::Onboard)
1317                             :Handles(Computer::Onboard);
1318
1319       That is, if a ":Handles" directive is given a name that includes a
1320       "::", it treats that name as a class name, rather than a method name.
1321       Then it checks that class's metadata (see INTROSPECTION), retrieves a
1322       list of all the method names from the class, and uses that as the list
1323       of method names to delegate.
1324
1325       Unlike an explicit ":Handles( method_name )", a ":Handles( Class::Name
1326       )" is tolerant of name collisions. If any method of "Class::Name" has
1327       the same name as another method or delegator that has already been
1328       installed in the current class, then ":Handles" just silently ignores
1329       that particular method, and doesn't try to replace the existing one.
1330       In other words, a ":Handles(Class::Name)" won't install a delegator to
1331       a method in "Class::Name" if that method is already being handled
1332       somewhere else by the current class.
1333
1334       For classes that don't have a "::" in their name (e.g., "DateTime" and
1335       "POE"), just append a "::" to the class name:
1336
1337        my @init_time :Field :Get(init_time)
1338                             :Type(    DateTime        )
1339                             :Default( DateTime->now() )
1340                             :Handles( DateTime::      );
1341
1342       Note that, when using the class-based version of ":Handles", every
1343       method is delegated with its name unchanged.  If some of the object's
1344       methods should be delegated under different names, you have to specify
1345       that explicitly (and beforehand):
1346
1347        my @onboard_computer :Field :Get(comp) :Type(Computer::Onboard)
1348                       # rename this method when delegating...
1349                             :Handles( iPod_control-->get_iPod )
1350                       # delegate everything else with names unchanged...
1351                             :Handles( Computer::Onboard );
1352
1353       "Handles" may be abbreviated to "Handle" or "Hand".
1354
1355       NOTES: Failure to add the appropriate object to the delegation field
1356       will lead to errors such as:  Can't call method "bar" on an undefined
1357       value.
1358
1359       Typos in ":Handles" attribute declarations will lead to errors such as:
1360       Can't locate object method "bat" via package "Foo".  Adding an object
1361       of the wrong class to the delegation field will lead to the same error,
1362       but can be avoided by adding a ":Type" attribute for the appropriate
1363       class.
1364

PERMISSIONS

1366   Restricted and Private Accessors
1367       By default, automatically generated accessors, can be called at any
1368       time.  In other words, their access permission is public.
1369
1370       If desired, accessors can be made restricted - in which case they can
1371       only be called from within the class and any child classes in the
1372       hierarchy that are derived from it - or private - such that they can
1373       only be called from within the accessors' class.  Here are examples of
1374       the syntax for adding permissions:
1375
1376        my @data     :Field :Std('Name' => 'data',     'Permission' => 'private');
1377        my @info     :Field :Set('Name' => 'set_info', 'Perm' => 'restricted');
1378        my @internal :Field :Acc('Name' => 'internal', 'Private' => 1);
1379        my @state    :Field :Get('Name' => 'state',    'Restricted' => 1);
1380
1381       When creating a standard pair of get_/set_ accessors, the permission
1382       setting is applied to both accessors.  If different permissions are
1383       required on the two accessors, then you'll have to use separate ":Get"
1384       and ":Set" attributes on the field.
1385
1386        # Create a private set method
1387        #  and a restricted get method on the 'foo' field
1388        my @foo :Field
1389                :Set('Name' => 'set_foo', 'Priv' => 1)
1390                :Get('Name' => 'get_foo', 'Rest' => 1);
1391
1392        # Create a restricted set method
1393        #  and a public get method on the 'bar' field
1394        my %bar :Field
1395                :Set('Name' => 'set_bar', 'Perm' => 'restrict')
1396                :Get(get_bar);
1397
1398       "Permission" may be abbreviated to "Perm"; "Private" may be abbreviated
1399       to "Priv"; and "Restricted" may be abbreviated to "Restrict".
1400
1401   Restricted and Private Methods
1402       In the same vein as describe above, access to methods can be narrowed
1403       by use of ":Restricted" and ":Private" attributes.
1404
1405        sub foo :Restricted
1406        {
1407            my $self = shift;
1408            ...
1409        }
1410
1411       Without either of these attributes, most methods have public access.
1412       If desired, you may explicitly label them with the ":Public" attribute.
1413
1414   Exemptions
1415       It is also possible to specify classes that are exempt from the
1416       Restricted and Private access permissions (i.e., the method may be
1417       called from those classes as well):
1418
1419        my %foo :Field
1420                :Acc('Name' => 'foo', 'Perm' => 'Restrict(Exempt::Class)')
1421                :Get(get_bar);
1422
1423        sub bar :Private(Some::Class, Another::Class)
1424        {
1425            my $self = shift;
1426            ...
1427        }
1428
1429       An example of when this might be needed is with delegation mechanisms.
1430
1431   Hidden Methods
1432       For subroutines marked with the following attributes (most of which are
1433       discussed later in this document):
1434
1435       :ID
1436       :PreInit
1437       :Init
1438       :Replicate
1439       :Destroy
1440       :Automethod
1441       :Dumper
1442       :Pumper
1443       :MOD_*_ATTRS
1444       :FETCH_*_ATTRS
1445
1446       Object::InsideOut normally renders them uncallable (hidden) to class
1447       and application code (as they should normally only be needed by
1448       Object::InsideOut itself).  If needed, this behavior can be overridden
1449       by adding the "Public", "Restricted" or "Private" attribute parameters:
1450
1451        sub _init :Init(private)    # Callable from within this class
1452        {
1453            my ($self, $args) = @_;
1454
1455            ...
1456        }
1457
1458   Restricted and Private Classes
1459       Permission for object creation on a class can be narrowed by adding a
1460       ":Restricted" or ":Private" flag to its "use Object::InsideOut ..."
1461       declaration.  This basically adds ":Restricted/:Private" permissions on
1462       the "->new()" method for that class.  Exemptions are also supported.
1463
1464        package Foo; {
1465            use Object::InsideOut;
1466            ...
1467        }
1468
1469        package Bar; {
1470            use Object::InsideOut 'Foo', ':Restricted(Ping, Pong)';
1471            ...
1472        }
1473
1474       In the above, class "Bar" inherits from class "Foo", and its
1475       constructor is restricted to itself, classes that inherit from "Bar",
1476       and the classes "Ping" and "Pong".
1477
1478       As constructors are inherited, any class that inherits from "Bar" would
1479       also be a restricted class.  To overcome this, any child class would
1480       need to add its own permission declaration:
1481
1482        package Baz; {
1483            use Object::InsideOut qw/Bar :Private(My::Class)/;
1484            ...
1485        }
1486
1487       Here, class "Baz" inherits from class "Bar", and its constructor is
1488       restricted to itself (i.e., private) and class "My::Class".
1489
1490       Inheriting from a ":Private" class is permitted, but objects cannot be
1491       created for that class unless it has a permission declaration of its
1492       own:
1493
1494        package Zork; {
1495            use Object::InsideOut qw/:Public Baz/;
1496            ...
1497        }
1498
1499       Here, class "Zork" inherits from class "Baz", and its constructor has
1500       unrestricted access.  (In general, don't use the ":Public" declaration
1501       for a class except to overcome constructor permissions inherited from
1502       parent classes.)
1503

TYPE CHECKING

1505       Object::InsideOut can be directed to add type-checking code to the
1506       set/combined accessors it generates, and to perform type checking on
1507       object initialization parameters.
1508
1509   Field Type Checking
1510       Type checking for a field can be specified by adding the ":Type"
1511       attribute to the field declaration:
1512
1513        my @count :Field :Type(numeric);
1514
1515        my @objs :Field :Type(list(My::Class));
1516
1517       The ":Type" attribute results in type checking code being added to
1518       set/combined accessors generated by Object::InsideOut, and will perform
1519       type checking on object initialization parameters processed by the
1520       ":Arg" attribute.
1521
1522       Available Types are:
1523
1524       'scalar'
1525           Permits anything that is not a reference.
1526
1527       'numeric'
1528           Can also be specified as "Num" or "Number".  This uses
1529           Scalar::Util::looks_like_number() to test the input value.
1530
1531       'list' or 'array'
1532       'list(_subtype_)' or 'array(_subtype_)'
1533           This type permits an accessor to accept multiple values (which are
1534           then placed in an array ref) or a single array ref.
1535
1536           For object initialization parameters, it permits a single value
1537           (which is then placed in an array ref) or an array ref.
1538
1539           When specified, the contents of the resulting array ref are checked
1540           against the specified subtype:
1541
1542           'scalar'
1543               Same as for the basic type above.
1544
1545           'numeric'
1546               Same as for the basic type above.
1547
1548           A class name
1549               Same as for the basic type below.
1550
1551           A reference type
1552               Any reference type (in all caps) as returned by ref()).
1553
1554       'ARRAY_ref'
1555       'ARRAY_ref(_subtype_)'
1556           This specifies that only a single array reference is permitted.
1557           Can also be specified as "ARRAYref".
1558
1559           When specified, the contents of the array ref are checked against
1560           the specified subtype as per the above.
1561
1562       'HASH'
1563           This type permits an accessor to accept multiple "key => value"
1564           pairs (which are then placed in a hash ref) or a single hash ref.
1565
1566           For object initialization parameters, only a single ref is
1567           permitted.
1568
1569       'HASH_ref'
1570           This specifies that only a single hash reference is permitted.  Can
1571           also be specified as "HASHref".
1572
1573       'SCALAR_ref'
1574           This type permits an accessor to accept a single scalar reference.
1575           Can also be specified as "SCALARref".
1576
1577       A class name
1578           This permits only an object of the specified class, or one of its
1579           sub-classes (i.e., type checking is done using "->isa()").  For
1580           example, "My::Class".  The class name "UNIVERSAL" permits any
1581           object.  The class name "Object::InsideOut" permits any object
1582           generated by an Object::InsideOut class.
1583
1584       Other reference type
1585           This permits only a reference of the specified type (as returned by
1586           ref()).  The type must be specified in all caps.  For example,
1587           "CODE".
1588
1589       The ":Type" attribute can also be supplied with a code reference to
1590       provide custom type checking.  The code ref may either be in the form
1591       of an anonymous subroutine, or a fully-qualified subroutine name.  The
1592       result of executing the code ref on the input argument should be a
1593       boolean value.  Here's some examples:
1594
1595        package My::Class; {
1596            use Object::InsideOut;
1597
1598            # Type checking using an anonymous subroutine
1599            #  (This checks that the argument is an object)
1600            my @data :Field :Type(sub { Scalar::Util::blessed($_[0]) })
1601                            :Acc(data);
1602
1603            # Type checking using a fully-qualified subroutine name
1604            my @num  :Field :Type(\&My::Class::positive)
1605                            :Acc(num);
1606
1607            # The type checking subroutine may be made 'Private'
1608            sub positive :Private
1609            {
1610                return (Scalar::Util::looks_like_number($_[0]) &&
1611                        ($_[0] > 0));
1612            }
1613        }
1614
1615   Type Checking on ":Init" Parameters
1616       For object initialization parameters that are sent to the ":Init"
1617       subroutine during object initialization, the parameter's type can be
1618       specified in the ":InitArgs" hash for that parameter using the same
1619       types as specified in the previous section.  For example:
1620
1621        my %init_args :InitArgs = (
1622            'COUNT' => {
1623                'Type' => 'numeric',
1624            },
1625            'OBJS' => {
1626                'Type' => 'list(My::Class)',
1627            },
1628        );
1629
1630       One exception involves custom type checking:  If referenced in an
1631       ":InitArgs" hash, the type checking subroutine cannot be made
1632       ":Private":
1633
1634        package My::Class; {
1635            use Object::InsideOut;
1636
1637            sub check_type   # Cannot be :Private
1638            {
1639               ...
1640            }
1641
1642            my %init_args :InitArgs = (
1643                'ARG' => {
1644                    'Type' => \&check_type,
1645                },
1646            );
1647
1648            ...
1649        }
1650
1651       Also, as shown, it also doesn't have to be a fully-qualified name.
1652

CUMULATIVE METHODS

1654       Normally, methods with the same name in a class hierarchy are masked
1655       (i.e., overridden) by inheritance - only the method in the most-derived
1656       class is called.  With cumulative methods, this masking is removed, and
1657       the same-named method is called in each of the classes within the
1658       hierarchy.  The return results from each call (if any) are then
1659       gathered together into the return value for the original method call.
1660       For example,
1661
1662        package My::Class; {
1663            use Object::InsideOut;
1664
1665            sub what_am_i :Cumulative
1666            {
1667                my $self = shift;
1668
1669                my $ima = (ref($self) eq __PACKAGE__)
1670                            ? q/I was created as a /
1671                            : q/My top class is /;
1672
1673                return ($ima . __PACKAGE__);
1674            }
1675        }
1676
1677        package My::Foo; {
1678            use Object::InsideOut 'My::Class';
1679
1680            sub what_am_i :Cumulative
1681            {
1682                my $self = shift;
1683
1684                my $ima = (ref($self) eq __PACKAGE__)
1685                            ? q/I was created as a /
1686                            : q/I'm also a /;
1687
1688                return ($ima . __PACKAGE__);
1689            }
1690        }
1691
1692        package My::Child; {
1693            use Object::InsideOut 'My::Foo';
1694
1695            sub what_am_i :Cumulative
1696            {
1697                my $self = shift;
1698
1699                my $ima = (ref($self) eq __PACKAGE__)
1700                            ? q/I was created as a /
1701                            : q/I'm in class /;
1702
1703                return ($ima . __PACKAGE__);
1704            }
1705        }
1706
1707        package main;
1708
1709        my $obj = My::Child->new();
1710        my @desc = $obj->what_am_i();
1711        print(join("\n", @desc), "\n");
1712
1713       produces:
1714
1715        My top class is My::Class
1716        I'm also a My::Foo
1717        I was created as a My::Child
1718
1719       When called in a list context (as in the above), the return results of
1720       cumulative methods are accumulated, and returned as a list.
1721
1722       In a scalar context, a results object is returned that segregates the
1723       results by class for each of the cumulative method calls.  Through
1724       overloading, this object can then be dereferenced as an array, hash,
1725       string, number, or boolean.  For example, the above could be rewritten
1726       as:
1727
1728        my $obj = My::Child->new();
1729        my $desc = $obj->what_am_i();        # Results object
1730        print(join("\n", @{$desc}), "\n");   # Dereference as an array
1731
1732       The following uses hash dereferencing:
1733
1734        my $obj = My::Child->new();
1735        my $desc = $obj->what_am_i();
1736        while (my ($class, $value) = each(%{$desc})) {
1737            print("Class $class reports:\n\t$value\n");
1738        }
1739
1740       and produces:
1741
1742        Class My::Class reports:
1743                My top class is My::Class
1744        Class My::Child reports:
1745                I was created as a My::Child
1746        Class My::Foo reports:
1747                I'm also a My::Foo
1748
1749       As illustrated above, cumulative methods are tagged with the
1750       ":Cumulative" attribute (or ":Cumulative(top down)"), and propagate
1751       from the top down through the class hierarchy (i.e., from the parent
1752       classes down through the child classes).  If tagged with
1753       ":Cumulative(bottom up)", they will propagated from the object's class
1754       upward through the parent classes.
1755

CHAINED METHODS

1757       In addition to ":Cumulative", Object::InsideOut provides a way of
1758       creating methods that are chained together so that their return values
1759       are passed as input arguments to other similarly named methods in the
1760       same class hierarchy.  In this way, the chained methods act as though
1761       they were piped together.
1762
1763       For example, imagine you had a method called "format_name" that formats
1764       some text for display:
1765
1766        package Subscriber; {
1767            use Object::InsideOut;
1768
1769            sub format_name {
1770                my ($self, $name) = @_;
1771
1772                # Strip leading and trailing whitespace
1773                $name =~ s/^\s+//;
1774                $name =~ s/\s+$//;
1775
1776                return ($name);
1777            }
1778        }
1779
1780       And elsewhere you have a second class that formats the case of names:
1781
1782        package Person; {
1783            use Lingua::EN::NameCase qw(nc);
1784            use Object::InsideOut;
1785
1786            sub format_name
1787            {
1788                my ($self, $name) = @_;
1789
1790                # Attempt to properly case names
1791                return (nc($name));
1792            }
1793        }
1794
1795       And you decide that you'd like to perform some formatting of your own,
1796       and then have all the parent methods apply their own formatting.
1797       Normally, if you have a single parent class, you'd just call the method
1798       directly with "$self->SUPER::format_name($name)", but if you have more
1799       than one parent class you'd have to explicitly call each method
1800       directly:
1801
1802        package Customer; {
1803            use Object::InsideOut qw(Person Subscriber);
1804
1805            sub format_name
1806            {
1807                my ($self, $name) = @_;
1808
1809                # Compress all whitespace into a single space
1810                $name =~ s/\s+/ /g;
1811
1812                $name = $self->Subscriber::format_name($name);
1813                $name = $self->Person::format_name($name);
1814
1815                return $name;
1816            }
1817        }
1818
1819       With Object::InsideOut, you'd add the ":Chained" attribute to each
1820       class's "format_name" method, and the methods will be chained together
1821       automatically:
1822
1823        package Subscriber; {
1824            use Object::InsideOut;
1825
1826            sub format_name :Chained
1827            {
1828                my ($self, $name) = @_;
1829
1830                # Strip leading and trailing whitespace
1831                $name =~ s/^\s+//;
1832                $name =~ s/\s+$//;
1833
1834                return ($name);
1835            }
1836        }
1837
1838        package Person; {
1839            use Lingua::EN::NameCase qw(nc);
1840            use Object::InsideOut;
1841
1842            sub format_name :Chained
1843            {
1844                my ($self, $name) = @_;
1845
1846                # Attempt to properly case names
1847                return (nc($name));
1848            }
1849        }
1850
1851        package Customer; {
1852            use Object::InsideOut qw(Person Subscriber);
1853
1854            sub format_name :Chained
1855            {
1856                my ($self, $name) = @_;
1857
1858                # Compress all whitespace into a single space
1859                $name =~ s/\s+/ /g;
1860
1861                return ($name);
1862            }
1863        }
1864
1865       So passing in someone's name to "format_name" in "Customer" would cause
1866       leading and trailing whitespace to be removed, then the name to be
1867       properly cased, and finally whitespace to be compressed to a single
1868       space.  The resulting $name would be returned to the caller:
1869
1870        my ($name) = $obj->format_name($name_raw);
1871
1872       Unlike ":Cumulative" methods, ":Chained" methods always returns an
1873       array - even if there is only one value returned.  Therefore,
1874       ":Chained" methods should always be called in an array context, as
1875       illustrated above.
1876
1877       The default direction is to chain methods from the parent classes at
1878       the top of the class hierarchy down through the child classes.  You may
1879       use the attribute ":Chained(top down)" to make this more explicit.
1880
1881       If you label the method with the ":Chained(bottom up)" attribute, then
1882       the chained methods are called starting with the object's class and
1883       working upward through the parent classes in the class hierarchy,
1884       similar to how ":Cumulative(bottom up)" works.
1885

ARGUMENT MERGING

1887       As mentioned under "Object Creation", the "->new()" method can take
1888       parameters that are passed in as combinations of "key => value" pairs
1889       and/or hash refs:
1890
1891        my $obj = My::Class->new(
1892            'param_X' => 'value_X',
1893            'param_Y' => 'value_Y',
1894            {
1895                'param_A' => 'value_A',
1896                'param_B' => 'value_B',
1897            },
1898            {
1899                'param_Q' => 'value_Q',
1900            },
1901        );
1902
1903       The parameters are merged into a single hash ref before they are
1904       processed.
1905
1906       Adding the ":MergeArgs" attribute to your methods gives them a similar
1907       capability.  Your method will then get two arguments:  The object and a
1908       single hash ref of the merged arguments.  For example:
1909
1910        package Foo; {
1911            use Object::InsideOut;
1912
1913            ...
1914
1915            sub my_method :MergeArgs {
1916                my ($self, $args) = @_;
1917
1918                my $param = $args->{'param'};
1919                my $data  = $args->{'data'};
1920                my $flag  = $args->{'flag'};
1921                ...
1922            }
1923        }
1924
1925        package main;
1926
1927        my $obj = Foo->new(...);
1928
1929        $obj->my_method( { 'data' => 42,
1930                           'flag' => 'true' },
1931                         'param' => 'foo' );
1932

ARGUMENT VALIDATION

1934       A number of users have asked about argument validation for methods:
1935       <http://www.cpanforum.com/threads/3204>.  For this, I recommend using
1936       Params::Validate:
1937
1938        package Foo; {
1939            use Object::InsideOut;
1940            use Params::Validate ':all';
1941
1942            sub foo
1943            {
1944                my $self = shift;
1945                my %args = validate(@_, { bar => 1 });
1946                my $bar = $args{bar};
1947                ...
1948            }
1949        }
1950
1951       Using Attribute::Params::Validate, attributes are used for argument
1952       validation specifications:
1953
1954        package Foo; {
1955            use Object::InsideOut;
1956            use Attribute::Params::Validate;
1957
1958            sub foo :method :Validate(bar => 1)
1959            {
1960                my $self = shift;
1961                my %args = @_;
1962                my $bar = $args{bar};
1963                ...
1964            }
1965        }
1966
1967       Note that in the above, Perl's ":method" attribute (in all lowercase)
1968       is needed.
1969
1970       There is some incompatibility between Attribute::Params::Validate and
1971       some of Object::InsideOut's attributes.  Namely, you cannot use
1972       ":Validate" with ":Private", ":Restricted", ":Cumulative", ":Chained"
1973       or ":MergeArgs".  In these cases, use the "validate()" function from
1974       Params::Validate instead.
1975

AUTOMETHODS

1977       There are significant issues related to Perl's "AUTOLOAD" mechanism
1978       that cause it to be ill-suited for use in a class hierarchy. Therefore,
1979       Object::InsideOut implements its own ":Automethod" mechanism to
1980       overcome these problems.
1981
1982       Classes requiring "AUTOLOAD"-type capabilities must provided a
1983       subroutine labeled with the ":Automethod" attribute.  The ":Automethod"
1984       subroutine will be called with the object and the arguments in the
1985       original method call (the same as for "AUTOLOAD").  The ":Automethod"
1986       subroutine should return either a subroutine reference that implements
1987       the requested method's functionality, or else just end with "return;"
1988       to indicate that it doesn't know how to handle the request.
1989
1990       Using its own "AUTOLOAD" subroutine (which is exported to every class),
1991       Object::InsideOut walks through the class tree, calling each
1992       ":Automethod" subroutine, as needed, to fulfill an unimplemented method
1993       call.
1994
1995       The name of the method being called is passed as $_ instead of
1996       $AUTOLOAD, and is not prefixed with the class name.  If the
1997       ":Automethod" subroutine also needs to access the $_ from the caller's
1998       scope, it is available as $CALLER::_.
1999
2000       Automethods can also be made to act as "CUMULATIVE METHODS" or "CHAINED
2001       METHODS".  In these cases, the ":Automethod" subroutine should return
2002       two values: The subroutine ref to handle the method call, and a string
2003       designating the type of method.  The designator has the same form as
2004       the attributes used to designate ":Cumulative" and ":Chained" methods:
2005
2006        ':Cumulative'  or  ':Cumulative(top down)'
2007        ':Cumulative(bottom up)'
2008        ':Chained'     or  ':Chained(top down)'
2009        ':Chained(bottom up)'
2010
2011       The following skeletal code illustrates how an ":Automethod" subroutine
2012       could be structured:
2013
2014        sub _automethod :Automethod
2015        {
2016            my $self = shift;
2017            my @args = @_;
2018
2019            my $method_name = $_;
2020
2021            # This class can handle the method directly
2022            if (...) {
2023                my $handler = sub {
2024                    my $self = shift;
2025                    ...
2026                    return ...;
2027                };
2028
2029                ### OPTIONAL ###
2030                # Install the handler so it gets called directly next time
2031                # no strict refs;
2032                # *{__PACKAGE__.'::'.$method_name} = $handler;
2033                ################
2034
2035                return ($handler);
2036            }
2037
2038            # This class can handle the method as part of a chain
2039            if (...) {
2040                my $chained_handler = sub {
2041                    my $self = shift;
2042                    ...
2043                    return ...;
2044                };
2045
2046                return ($chained_handler, ':Chained');
2047            }
2048
2049            # This class cannot handle the method request
2050            return;
2051        }
2052
2053       Note: The OPTIONAL code above for installing the generated handler as a
2054       method should not be used with ":Cumulative" or ":Chained" automethods.
2055

OBJECT SERIALIZATION

2057   Basic Serialization
2058       my $array_ref = $obj->dump();
2059       my $string = $obj->dump(1);
2060           Object::InsideOut exports a method called "->dump()" to each class
2061           that returns either a Perl or a string representation of the object
2062           that invokes the method.
2063
2064           The Perl representation is returned when "->dump()" is called
2065           without arguments.  It consists of an array ref whose first element
2066           is the name of the object's class, and whose second element is a
2067           hash ref containing the object's data.  The object data hash ref
2068           contains keys for each of the classes that make up the object's
2069           hierarchy. The values for those keys are hash refs containing
2070           "key => value" pairs for the object's fields.  For example:
2071
2072            [
2073              'My::Class::Sub',
2074              {
2075                'My::Class' => {
2076                                 'data' => 'value'
2077                               },
2078                'My::Class::Sub' => {
2079                                      'life' => 42
2080                                    }
2081              }
2082            ]
2083
2084           The name for an object field (data and life in the example above)
2085           can be specified by adding the ":Name" attribute to the field:
2086
2087            my @life :Field :Name(life);
2088
2089           If the ":Name" attribute is not used, then the name for a field
2090           will be either the name associated with an ":All" or ":Arg"
2091           attribute, its get method name, its set method name, or, failing
2092           all that, a string of the form "ARRAY(0x...)" or "HASH(0x...)".
2093
2094           When called with a true argument, "->dump()" returns a string
2095           version of the Perl representation using Data::Dumper.
2096
2097           Note that using Data::Dumper directly on an inside-out object will
2098           not produce the desired results (it'll just output the contents of
2099           the scalar ref).  Also, if inside-out objects are stored inside
2100           other structures, a dump of those structures will not contain the
2101           contents of the object's fields.
2102
2103           In the event of a method naming conflict, the "->dump()" method can
2104           be called using its fully-qualified name:
2105
2106            my $dump = $obj->Object::InsideOut::dump();
2107
2108       my $obj = Object::InsideOut->pump($data);
2109           "Object::InsideOut->pump()" takes the output from the "->dump()"
2110           method, and returns an object that is created using that data.  If
2111           $data is the array ref returned by using "$obj->dump()", then the
2112           data is inserted directly into the corresponding fields for each
2113           class in the object's class hierarchy.  If $data is the string
2114           returned by using "$obj->dump(1)", then it is "eval"ed to turn it
2115           into an array ref, and then processed as above.
2116
2117           Caveats: If any of an object's fields are dumped to field name keys
2118           of the form "ARRAY(0x...)" or "HASH(0x...)" (see above), then the
2119           data will not be reloadable using "Object::InsideOut->pump()".  To
2120           overcome this problem, the class developer must either add ":Name"
2121           attributes to the ":Field" declarations (see above), or provide a
2122           ":Dumper"/":Pumper" pair of subroutines as described below.
2123
2124           Dynamically altering a class (e.g., using ->create_field()) after
2125           objects have been dumped will result in "undef" fields when pumped
2126           back in regardless of whether or not the added fields have
2127           defaults.
2128
2129           Modifying the output from "->dump()", and then feeding it into
2130           "Object::InsideOut->pump()" will work, but is not specifically
2131           supported.  If you know what you're doing, fine, but you're on your
2132           own.
2133
2134       ":Dumper" Subroutine Attribute
2135           If a class requires special processing to dump its data, then it
2136           can provide a subroutine labeled with the ":Dumper" attribute.
2137           This subroutine will be sent the object that is being dumped.  It
2138           may then return any type of scalar the developer deems appropriate.
2139           Usually, this would be a hash ref containing "key => value" pairs
2140           for the object's fields.  For example:
2141
2142            my @data :Field;
2143
2144            sub _dump :Dumper
2145            {
2146                my $obj = $_[0];
2147
2148                my %field_data;
2149                $field_data{'data'} = $data[$$obj];
2150
2151                return (\%field_data);
2152            }
2153
2154           Just be sure not to call your ":Dumper" subroutine "dump" as that
2155           is the name of the dump method exported by Object::InsideOut as
2156           explained above.
2157
2158       ":Pumper" Subroutine Attribute
2159           If a class supplies a ":Dumper" subroutine, it will most likely
2160           need to provide a complementary ":Pumper" labeled subroutine that
2161           will be used as part of creating an object from dumped data using
2162           "Object::InsideOut->pump()".  The subroutine will be supplied the
2163           new object that is being created, and whatever scalar was returned
2164           by the ":Dumper" subroutine.  The corresponding ":Pumper" for the
2165           example ":Dumper" above would be:
2166
2167            sub _pump :Pumper
2168            {
2169                my ($obj, $field_data) = @_;
2170
2171                $obj->set(\@data, $field_data->{'data'});
2172            }
2173
2174   Storable
2175       Object::InsideOut also supports object serialization using the Storable
2176       module.  There are two methods for specifying that a class can be
2177       serialized using Storable.  The first method involves adding Storable
2178       to the Object::InsideOut declaration in your package:
2179
2180        package My::Class; {
2181            use Object::InsideOut qw(Storable);
2182            ...
2183        }
2184
2185       and adding "use Storable;" in your application.  Then you can use the
2186       "->store()" and "->freeze()" methods to serialize your objects, and the
2187       "retrieve()" and "thaw()" subroutines to de-serialize them.
2188
2189        package main;
2190        use Storable;
2191        use My::Class;
2192
2193        my $obj = My::Class->new(...);
2194        $obj->store('/tmp/object.dat');
2195        ...
2196        my $obj2 = retrieve('/tmp/object.dat');
2197
2198       The other method of specifying Storable serialization involves setting
2199       a "::storable" variable inside a "BEGIN" block for the class prior to
2200       its use:
2201
2202        package main;
2203        use Storable;
2204
2205        BEGIN {
2206            $My::Class::storable = 1;
2207        }
2208        use My::Class;
2209
2210       NOTE: The caveats discussed above for the "->pump()" method are also
2211       applicable when using the Storable module.
2212

OBJECT COERCION

2214       Object::InsideOut provides support for various forms of object coercion
2215       through the overload mechanism.  For instance, if you want an object to
2216       be usable directly in a string, you would supply a subroutine in your
2217       class labeled with the ":Stringify" attribute:
2218
2219        sub as_string :Stringify
2220        {
2221            my $self = $_[0];
2222            my $string = ...;
2223            return ($string);
2224        }
2225
2226       Then you could do things like:
2227
2228        print("The object says, '$obj'\n");
2229
2230       For a boolean context, you would supply:
2231
2232        sub as_bool :Boolify
2233        {
2234            my $self = $_[0];
2235            my $true_or_false = ...;
2236            return ($true_or_false);
2237        }
2238
2239       and use it in this manner:
2240
2241        if (! defined($obj)) {
2242            # The object is undefined
2243            ....
2244
2245        } elsif (! $obj) {
2246            # The object returned a false value
2247            ...
2248        }
2249
2250       The following coercion attributes are supported:
2251
2252       :Stringify
2253       :Numerify
2254       :Boolify
2255       :Arrayify
2256       :Hashify
2257       :Globify
2258       :Codify
2259
2260       Coercing an object to a scalar (":Scalarify") is not supported as $$obj
2261       is the ID of the object and cannot be overridden.
2262

CLONING

2264   Object Cloning
2265       Copies of objects can be created using the "->clone()" method which is
2266       exported by Object::InsideOut to each class:
2267
2268        my $obj2 = $obj->clone();
2269
2270       When called without arguments, "->clone()" creates a shallow copy of
2271       the object, meaning that any complex data structures (i.e., array, hash
2272       or scalar refs) stored in the object will be shared with its clone.
2273
2274       Calling "->clone()" with a true argument:
2275
2276        my $obj2 = $obj->clone(1);
2277
2278       creates a deep copy of the object such that internally held array, hash
2279       or scalar refs are replicated and stored in the newly created clone.
2280
2281       Deep cloning can also be controlled at the field level, and is covered
2282       in the next section.
2283
2284       Note that cloning does not clone internally held objects.  For example,
2285       if $foo contains a reference to $bar, a clone of $foo will also contain
2286       a reference to $bar; not a clone of $bar.  If such behavior is needed,
2287       it must be provided using a :Replicate subroutine.
2288
2289   Field Cloning
2290       Object cloning can be controlled at the field level such that specified
2291       fields are deeply copied when "->clone()" is called without any
2292       arguments.  This is done by adding the ":Deep" attribute to the field:
2293
2294        my @data :Field :Deep;
2295

WEAK FIELDS

2297       Frequently, it is useful to store weakened references to data or
2298       objects in a field.  Such a field can be declared as ":Weak" so that
2299       data (i.e., references) set via Object::InsideOut generated accessors,
2300       parameter processing using ":Arg", the "->set()" method, etc., will
2301       automatically be weakened after being stored in the field array/hash.
2302
2303        my @data :Field :Weak;
2304
2305       NOTE: If data in a weak field is set directly (i.e., the "->set()"
2306       method is not used), then weaken() must be invoked on the stored
2307       reference afterwards:
2308
2309        $self->set(\@field, $data);
2310        Scalar::Util::weaken($field[$$self]);
2311
2312       (This is another reason why the "->set()" method is recommended for
2313       setting field data within class code.)
2314

DYNAMIC FIELD CREATION

2316       Normally, object fields are declared as part of the class code.
2317       However, some classes may need the capability to create object fields
2318       on-the-fly, for example, as part of an ":Automethod".
2319       Object::InsideOut provides a class method for this:
2320
2321        # Dynamically create a hash field with standard accessors
2322        My::Class->create_field('%'.$fld, ":Std($fld)");
2323
2324       The first argument is the class into which the field will be added.
2325       The second argument is a string containing the name of the field
2326       preceded by either a "@" or "%" to declare an array field or hash
2327       field, respectively.  The remaining string arguments should be
2328       attributes declaring accessors and the like.  The ":Field" attribute is
2329       assumed, and does not need to be added to the attribute list.  For
2330       example:
2331
2332        My::Class->create_field('@data', ":Type(numeric)",
2333                                         ":Acc(data)");
2334
2335        My::Class->create_field('@obj', ":Type(Some::Class)",
2336                                        ":Acc(obj)",
2337                                        ":Weak");
2338
2339       Field creation will fail if you try to create an array field within a
2340       class whose hierarchy has been declared :hash_only.
2341
2342       Here's an example of an ":Automethod" subroutine that uses dynamic
2343       field creation:
2344
2345        package My::Class; {
2346            use Object::InsideOut;
2347
2348            sub _automethod :Automethod
2349            {
2350                my $self = $_[0];
2351                my $class = ref($self) || $self;
2352                my $method = $_;
2353
2354                # Extract desired field name from get_/set_ method name
2355                my ($fld_name) = $method =~ /^[gs]et_(.*)$/;
2356                if (! $fld_name) {
2357                    return;    # Not a recognized method
2358                }
2359
2360                # Create the field and its standard accessors
2361                $class->create_field('@'.$fld_name, ":Std($fld_name)");
2362
2363                # Return code ref for newly created accessor
2364                no strict 'refs';
2365                return *{$class.'::'.$method}{'CODE'};
2366            }
2367        }
2368

RUNTIME INHERITANCE

2370       The class method "->add_class()" provides the capability to dynamically
2371       add classes to a class hierarchy at runtime.
2372
2373       For example, suppose you had a simple state class:
2374
2375        package Trait::State; {
2376            use Object::InsideOut;
2377
2378            my %state :Field :Set(state);
2379        }
2380
2381       This could be added to another class at runtime using:
2382
2383        My::Class->add_class('Trait::State');
2384
2385       This permits, for example, application code to dynamically modify a
2386       class without having it create an actual sub-class.
2387

PREPROCESSING

2389   Parameter Preprocessing
2390       You can specify a code ref (either in the form of an anonymous
2391       subroutine, or a subroutine name) for an object initialization
2392       parameter that will be called on that parameter prior to taking any of
2393       the other parameter actions described above.  Here's an example:
2394
2395        package My::Class; {
2396            use Object::InsideOut;
2397
2398            # The parameter preprocessing subroutine
2399            sub preproc
2400            {
2401                my ($class, $param, $spec, $obj, $value) = @_;
2402
2403                # Preform parameter preprocessing
2404                ...
2405
2406                # Return result
2407                return ...;
2408            }
2409
2410            my @data :Field
2411                     :Arg('Name' => 'DATA', 'Preprocess' => \&My::Class::preproc);
2412
2413            my %init_args :InitArgs = (
2414                'PARAM' => {
2415                    'Preprocess' => \&preproc,
2416                },
2417            );
2418
2419            ...
2420        }
2421
2422       When used in the ":Arg" attribute, the subroutine name must be fully-
2423       qualified, as illustrated.  Further, if not referenced in the
2424       ":InitArgs" hash, the preprocessing subroutine can be given the
2425       ":Private" attribute.
2426
2427       As the above illustrates, the parameter preprocessing subroutine is
2428       sent five arguments:
2429
2430       ·   The name of the class associated with the parameter
2431
2432           This would be "My::Class" in the example above.
2433
2434       ·   The name of the parameter
2435
2436           Either "DATA" or "PARAM" in the example above.
2437
2438       ·   A hash ref of the parameter's specifiers
2439
2440           This is either a hash ref containing the ":Arg" attribute
2441           parameters, or the hash ref paired to the parameter's key in the
2442           ":InitArgs" hash.
2443
2444       ·   The object being initialized
2445
2446       ·   The parameter's value
2447
2448           This is the value assigned to the parameter in the "->new()"
2449           method's argument list.  If the parameter was not provided to
2450           "->new()", then "undef" will be sent.
2451
2452       The return value of the preprocessing subroutine will then be assigned
2453       to the parameter.
2454
2455       Be careful about what types of data the preprocessing subroutine tries
2456       to make use of "external" to the arguments supplied.  For instance,
2457       because the order of parameter processing is not specified, the
2458       preprocessing subroutine cannot rely on whether or not some other
2459       parameter is set.  Such processing would need to be done in the ":Init"
2460       subroutine.  It can, however, make use of object data set by classes
2461       higher up in the class hierarchy.  (That is why the object is provided
2462       as one of the arguments.)
2463
2464       Possible uses for parameter preprocessing include:
2465
2466       ·   Overriding the supplied value (or even deleting it by returning
2467           "undef")
2468
2469       ·   Providing a dynamically-determined default value
2470
2471       Preprocess may be abbreviated to Preproc or Pre.
2472
2473   Set Accessor Preprocessing
2474       You can specify a code ref (either in the form of an anonymous
2475       subroutine, or a fully-qualified subroutine name) for a set/combined
2476       accessor that will be called on the arguments supplied to the accessor
2477       prior to its taking the usual actions of type checking and adding the
2478       data to the field.  Here's an example:
2479
2480        package My::Class; {
2481            use Object::InsideOut;
2482
2483            my @data :Field
2484                     :Acc('Name' => 'data', 'Preprocess' => \&My::Class::preproc);
2485
2486            # The set accessor preprocessing subroutine may be made 'Private'
2487            sub preproc :Private
2488            {
2489                my ($self, $field, @args) = @_;
2490
2491                # Preform preprocessing on the accessor's arguments
2492                ...
2493
2494                # Return result
2495                return ...;
2496            }
2497        }
2498
2499       As the above illustrates, the accessor preprocessing subroutine is sent
2500       the following arguments:
2501
2502       ·   The object used to invoke the accessor
2503
2504       ·   A reference to the field associated with the accessor
2505
2506       ·   The argument(s) sent to the accessor
2507
2508           There will always be at least one argument.
2509
2510       Usually, the preprocessing subroutine would return just a single value.
2511       For fields declared as type "List", multiple values may be returned.
2512
2513       Following preprocessing, the set accessor will operate on whatever
2514       value(s) are returned by the preprocessing subroutine.
2515

SPECIAL PROCESSING

2517   Object ID
2518       By default, the ID of an object is derived from a sequence counter for
2519       the object's class hierarchy.  This should suffice for nearly all cases
2520       of class development.  If there is a special need for the module code
2521       to control the object ID (see Math::Random::MT::Auto as an example),
2522       then a subroutine labelled with the ":ID" attribute can be specified:
2523
2524        sub _id :ID
2525        {
2526            my $class = $_[0];
2527
2528            # Generate/determine a unique object ID
2529            ...
2530
2531            return ($id);
2532        }
2533
2534       The ID returned by your subroutine can be any kind of regular scalar
2535       (e.g., a string or a number).  However, if the ID is something other
2536       than a low-valued integer, then you will have to architect all your
2537       classes using hashes for the object fields.  See "HASH ONLY CLASSES"
2538       for details.
2539
2540       Within any class hierarchy, only one class may specify an ":ID"
2541       subroutine.
2542
2543   Object Replication
2544       Object replication occurs explicitly when the "->clone()" method is
2545       called on an object, and implicitly when threads are created in a
2546       threaded application.  In nearly all cases, Object::InsideOut will take
2547       care of all the details for you.
2548
2549       In rare cases, a class may require special handling for object
2550       replication.  It must then provide a subroutine labeled with the
2551       ":Replicate" attribute.  This subroutine will be sent three arguments:
2552       The parent and the cloned objects, and a flag:
2553
2554        sub _replicate :Replicate
2555        {
2556            my ($parent, $clone, $flag) = @_;
2557
2558            # Special object replication processing
2559            if ($clone eq 'CLONE') {
2560               # Handling for thread cloning
2561               ...
2562            } elsif ($clone eq 'deep') {
2563               # Deep copy of the parent
2564               ...
2565            } else {
2566               # Shallow copying
2567               ...
2568            }
2569        }
2570
2571       In the case of thread cloning, $flag will be set to the 'CLONE', and
2572       the $parent object is just a non-blessed anonymous scalar reference
2573       that contains the ID for the object in the parent thread.
2574
2575       When invoked via the "->clone()" method, $flag will be either an empty
2576       string which denotes that a shallow copy is being produced for the
2577       clone, or $flag will be set to 'deep' indicating a deep copy is being
2578       produced.
2579
2580       The ":Replicate" subroutine only needs to deal with the special
2581       replication processing needed by the object:  Object::InsideOut will
2582       handle all the other details.
2583
2584   Object Destruction
2585       Object::InsideOut exports a "DESTROY" method to each class that deletes
2586       an object's data from the object field arrays (hashes).  If a class
2587       requires additional destruction processing (e.g., closing filehandles),
2588       then it must provide a subroutine labeled with the ":Destroy"
2589       attribute.  This subroutine will be sent the object that is being
2590       destroyed:
2591
2592        sub _destroy :Destroy
2593        {
2594            my $obj = $_[0];
2595
2596            # Special object destruction processing
2597        }
2598
2599       The ":Destroy" subroutine only needs to deal with the special
2600       destruction processing:  The "DESTROY" method will handle all the other
2601       details of object destruction.
2602

FOREIGN CLASS INHERITANCE

2604       Object::InsideOut supports inheritance from foreign (i.e.,
2605       non-Object::InsideOut) classes.  This means that your classes can
2606       inherit from other Perl class, and access their methods from your own
2607       objects.
2608
2609       One method of declaring foreign class inheritance is to add the class
2610       name to the Object::InsideOut declaration inside your package:
2611
2612        package My::Class; {
2613            use Object::InsideOut qw(Foreign::Class);
2614            ...
2615        }
2616
2617       This allows you to access the foreign class's static (i.e., class)
2618       methods from your own class.  For example, suppose "Foreign::Class" has
2619       a class method called "foo".  With the above, you can access that
2620       method using "My::Class->foo()" instead.
2621
2622       Multiple foreign inheritance is supported, as well:
2623
2624        package My::Class; {
2625            use Object::InsideOut qw(Foreign::Class Other::Foreign::Class);
2626            ...
2627        }
2628
2629       $self->inherit($obj, ...);
2630           To use object methods from foreign classes, an object must inherit
2631           from an object of that class.  This would normally be done inside a
2632           class's ":Init" subroutine:
2633
2634            package My::Class; {
2635                use Object::InsideOut qw(Foreign::Class);
2636
2637                sub init :Init
2638                {
2639                    my ($self, $args) = @_;
2640
2641                    my $foreign_obj = Foreign::Class->new(...);
2642                    $self->inherit($foreign_obj);
2643                }
2644            }
2645
2646           Thus, with the above, if "Foreign::Class" has an object method
2647           called "bar", you can call that method from your own objects:
2648
2649            package main;
2650
2651            my $obj = My::Class->new();
2652            $obj->bar();
2653
2654           Object::InsideOut's "AUTOLOAD" subroutine handles the dispatching
2655           of the "->bar()" method call using the internally held inherited
2656           object (in this case, $foreign_obj).
2657
2658           Multiple inheritance is supported, as well:  You can call the
2659           "->inherit()" method multiple times, or make just one call with all
2660           the objects to be inherited from.
2661
2662           "->inherit()" is a restricted method.  In other words, you cannot
2663           use it on an object outside of code belonging to the object's class
2664           tree (e.g., you can't call it from application code).
2665
2666           In the event of a method naming conflict, the "->inherit()" method
2667           can be called using its fully-qualified name:
2668
2669            $self->Object::InsideOut::inherit($obj);
2670
2671       my @objs = $self->heritage();
2672       my $obj = $self->heritage($class);
2673       my @objs = $self->heritage($class1, $class2, ...);
2674           Your class code can retrieve any inherited objects using the
2675           "->heritage()" method. When called without any arguments, it
2676           returns a list of any objects that were stored by the calling class
2677           using the calling object.  In other words, if class "My::Class"
2678           uses object $obj to store foreign objects $fobj1 and $fobj2, then
2679           later on in class "My::Class", "$obj->heritage()" will return
2680           $fobj1 and $fobj2.
2681
2682           "->heritage()" can also be called with one or more class name
2683           arguments.  In this case, only objects of the specified class(es)
2684           are returned.
2685
2686           In the event of a method naming conflict, the "->heritage()" method
2687           can be called using its fully-qualified name:
2688
2689            my @objs = $self->Object::InsideOut::heritage();
2690
2691       $self->disinherit($class [, ...])
2692       $self->disinherit($obj [, ...])
2693           The "->disinherit()" method disassociates (i.e., deletes) the
2694           inheritance of foreign object(s) from an object.  The foreign
2695           objects may be specified by class, or using the actual inherited
2696           object (retrieved via "->heritage()", for example).
2697
2698           The call is only effective when called inside the class code that
2699           established the initial inheritance.  In other words, if an
2700           inheritance is set up inside a class, then disinheritance can only
2701           be done from inside that class.
2702
2703           In the event of a method naming conflict, the "->disinherit()"
2704           method can be called using its fully-qualified name:
2705
2706            $self->Object::InsideOut::disinherit($obj [, ...])
2707
2708       NOTE:  With foreign inheritance, you only have access to class and
2709       object methods.  The encapsulation of the inherited objects is strong,
2710       meaning that only the class where the inheritance takes place has
2711       direct access to the inherited object.  If access to the inherited
2712       objects themselves, or their internal hash fields (in the case of
2713       blessed hash objects), is needed outside the class, then you'll need to
2714       write your own accessors for that.
2715
2716       LIMITATION:  You cannot use fully-qualified method names to access
2717       foreign methods (when encapsulated foreign objects are involved).
2718       Thus, the following will not work:
2719
2720        my $obj = My::Class->new();
2721        $obj->Foreign::Class::bar();
2722
2723       Normally, you shouldn't ever need to do the above:  "$obj->bar()" would
2724       suffice.
2725
2726       The only time this may be an issue is when the native class overrides
2727       an inherited foreign class's method (e.g., "My::Class" has its own
2728       "->bar()" method).  Such overridden methods are not directly callable.
2729       If such overriding is intentional, then this should not be an issue:
2730       No one should be writing code that tries to by-pass the override.
2731       However, if the overriding is accidentally, then either the native
2732       method should be renamed, or the native class should provide a wrapper
2733       method so that the functionality of the overridden method is made
2734       available under a different name.
2735
2736   "use base" and Fully-qualified Method Names
2737       The foreign inheritance methodology handled by the above is predicated
2738       on non-Object::InsideOut classes that generate their own objects and
2739       expect their object methods to be invoked via those objects.
2740
2741       There are exceptions to this rule:
2742
2743       1. Foreign object methods that expect to be invoked via the inheriting
2744       class's object, or foreign object methods that don't care how they are
2745       invoked (i.e., they don't make reference to the invoking object).
2746           This is the case where a class provides auxiliary methods for your
2747           objects, but from which you don't actually create any objects
2748           (i.e., there is no corresponding foreign object, and
2749           "$obj->inherit($foreign)" is not used.)
2750
2751           In this case, you can either:
2752
2753           a. Declare the foreign class using the standard method (i.e.,
2754           "use Object::InsideOut qw(Foreign::Class);"), and invoke its
2755           methods using their full path (e.g.,
2756           "$obj->Foreign::Class::method();"); or
2757
2758           b. You can use the base pragma so that you don't have to use the
2759           full path for foreign methods.
2760
2761            package My::Class; {
2762                use Object::InsideOut;
2763                use base 'Foreign::Class';
2764                ...
2765            }
2766
2767           The former scheme is faster.
2768
2769       2. Foreign class methods that expect to be invoked via the inheriting
2770       class.
2771           As with the above, you can either invoke the class methods using
2772           their full path (e.g., "My::Class->Foreign::Class::method();"), or
2773           you can "use base" so that you don't have to use the full path.
2774           Again, using the full path is faster.
2775
2776           Class::Singleton is an example of this type of class.
2777
2778       3. Class methods that don't care how they are invoked (i.e., they don't
2779       make reference to the invoking class).
2780           In this case, you can either use
2781           "use Object::InsideOut qw(Foreign::Class);" for consistency, or use
2782           "use base qw(Foreign::Class);" if (slightly) better performance is
2783           needed.
2784
2785       If you're not familiar with the inner workings of the foreign class
2786       such that you don't know if or which of the above exceptions applies,
2787       then the formulaic approach would be to first use the documented method
2788       for foreign inheritance (i.e.,
2789       "use Object::InsideOut qw(Foreign::Class);").  If that works, then I
2790       strongly recommend that you just use that approach unless you have a
2791       good reason not to.  If it doesn't work, then try "use base".
2792

INTROSPECTION

2794       For Perl 5.8.0 and later, Object::InsideOut provides an introspection
2795       API that allow you to obtain metadata on a class's hierarchy,
2796       constructor parameters, and methods.
2797
2798       my $meta = My::Class->meta();
2799       my $meta = $obj->meta();
2800           The "->meta()" method, which is exported by Object::InsideOut to
2801           each class, returns an Object::InsideOut::Metadata object which can
2802           then be queried for information about the invoking class or
2803           invoking object's class:
2804
2805            # Get an object's class hierarchy
2806            my @classes = $obj->meta()->get_classes();
2807
2808            # Get info on the args for a class's constructor (i.e., ->new() parameters)
2809            my %args = My::Class->meta()->get_args();
2810
2811            # Get info on the methods that can be called by an object
2812            my %methods = $obj->meta()->get_methods();
2813
2814       My::Class->isa();
2815       $obj->isa();
2816           When called in an array context, calling "->isa()" without any
2817           arguments on an Object::InsideOut class or object returns a list of
2818           the classes in the class hierarchy for that class or object, and is
2819           equivalent to:
2820
2821            my @classes = $obj->meta()->get_classes();
2822
2823           When called in a scalar context, it returns an array ref containing
2824           the classes.
2825
2826       My::Class->can();
2827       $obj->can();
2828           When called in an array context, calling "->can()" without any
2829           arguments on an Object::InsideOut class or object returns a list of
2830           the method names for that class or object, and is equivalent to:
2831
2832            my %methods = $obj->meta()->get_methods();
2833            my @methods = keys(%methods);
2834
2835           When called in a scalar context, it returns an array ref containing
2836           the method names.
2837
2838       See Object::InsideOut::Metadata for more details.
2839

THREAD SUPPORT

2841       For Perl 5.8.1 and later, Object::InsideOut fully supports threads
2842       (i.e., is thread safe), and supports the sharing of Object::InsideOut
2843       objects between threads using threads::shared.
2844
2845       To use Object::InsideOut in a threaded application, you must put
2846       "use threads;" at the beginning of the application.  (The use of
2847       "require threads;" after the program is running is not supported.)  If
2848       object sharing is to be utilized, then "use threads::shared;" should
2849       follow.
2850
2851       If you just "use threads;", then objects from one thread will be copied
2852       and made available in a child thread.
2853
2854       The addition of "use threads::shared;" in and of itself does not alter
2855       the behavior of Object::InsideOut objects.  The default behavior is to
2856       not share objects between threads (i.e., they act the same as with
2857       "use threads;" alone).
2858
2859       To enable the sharing of objects between threads, you must specify
2860       which classes will be involved with thread object sharing.  There are
2861       two methods for doing this.  The first involves setting a "::shared"
2862       variable (inside a "BEGIN" block) for the class prior to its use:
2863
2864        use threads;
2865        use threads::shared;
2866
2867        BEGIN {
2868            $My::Class::shared = 1;
2869        }
2870        use My::Class;
2871
2872       The other method is for a class to add a ":SHARED" flag to its
2873       "use Object::InsideOut ..." declaration:
2874
2875        package My::Class; {
2876            use Object::InsideOut ':SHARED';
2877            ...
2878        }
2879
2880       When either sharing flag is set for one class in an object hierarchy,
2881       then all the classes in the hierarchy are affected.
2882
2883       If a class cannot support thread object sharing (e.g., one of the
2884       object fields contains code refs [which Perl cannot share between
2885       threads]), it should specifically declare this fact:
2886
2887        package My::Class; {
2888            use Object::InsideOut ':NOT_SHARED';
2889            ...
2890        }
2891
2892       However, you cannot mix thread object sharing classes with non-sharing
2893       classes in the same class hierarchy:
2894
2895        use threads;
2896        use threads::shared;
2897
2898        package My::Class; {
2899            use Object::InsideOut ':SHARED';
2900            ...
2901        }
2902
2903        package Other::Class; {
2904            use Object::InsideOut ':NOT_SHARED';
2905            ...
2906        }
2907
2908        package My::Derived; {
2909            use Object::InsideOut qw(My::Class Other::Class);   # ERROR!
2910            ...
2911        }
2912
2913       Here is a complete example with thread object sharing enabled:
2914
2915        use threads;
2916        use threads::shared;
2917
2918        package My::Class; {
2919            use Object::InsideOut ':SHARED';
2920
2921            # One list-type field
2922            my @data :Field :Type(list) :Acc(data);
2923        }
2924
2925        package main;
2926
2927        # New object
2928        my $obj = My::Class->new();
2929
2930        # Set the object's 'data' field
2931        $obj->data(qw(foo bar baz));
2932
2933        # Print out the object's data
2934        print(join(', ', @{$obj->data()}), "\n");       # "foo, bar, baz"
2935
2936        # Create a thread and manipulate the object's data
2937        my $rc = threads->create(
2938                sub {
2939                    # Read the object's data
2940                    my $data = $obj->data();
2941                    # Print out the object's data
2942                    print(join(', ', @{$data}), "\n");  # "foo, bar, baz"
2943                    # Change the object's data
2944                    $obj->data(@$data[1..2], 'zooks');
2945                    # Print out the object's modified data
2946                    print(join(', ', @{$obj->data()}), "\n");  # "bar, baz, zooks"
2947                    return (1);
2948                }
2949            )->join();
2950
2951        # Show that changes in the object are visible in the parent thread
2952        # I.e., this shows that the object was indeed shared between threads
2953        print(join(', ', @{$obj->data()}), "\n");       # "bar, baz, zooks"
2954

HASH ONLY CLASSES

2956       For performance considerations, it is recommended that arrays be used
2957       for class fields whenever possible.  The only time when hash-bases
2958       fields are required is when a class must provide its own object ID, and
2959       those IDs are something other than low-valued integers.  In this case,
2960       hashes must be used for fields not only in the class that defines the
2961       object ID subroutine, but also in every class in any class hierarchy
2962       that include such a class.
2963
2964       The hash only requirement can be enforced by adding the ":HASH_ONLY"
2965       flag to a class's "use Object::InsideOut ..." declaration:
2966
2967        package My::Class; {
2968            use Object::InsideOut ':hash_only';
2969
2970            ...
2971        }
2972
2973       This will cause Object::Inside to check every class in any class
2974       hierarchy that includes such flagged classes to make sure their fields
2975       are hashes and not arrays.  It will also fail any ->create_field() call
2976       that tries to create an array-based field in any such class.
2977

SECURITY

2979       In the default case where Object::InsideOut provides object IDs that
2980       are sequential integers, it is possible to hack together a fake
2981       Object::InsideOut object, and so gain access to another object's data:
2982
2983        my $fake = bless(\do{my $scalar}, 'Some::Class');
2984        $$fake = 86;   # ID of another object
2985        my $stolen = $fake->get_data();
2986
2987       Why anyone would try to do this is unknown.  How this could be used for
2988       any sort of malicious exploitation is also unknown.  However, if
2989       preventing this sort of security issue is a requirement, it can be
2990       accomplished by adding the ":SECURE" flag to a class's
2991       "use Object::InsideOut ..." declaration:
2992
2993        package My::Class; {
2994            use Object::InsideOut ':SECURE';
2995
2996            ...
2997        }
2998
2999       This places the module "Object::InsideOut::Secure" in the class
3000       hierarchy.  Object::InsideOut::Secure provides an :ID subroutine that
3001       generates random integers for object IDs, thus preventing other code
3002       from being able to create fake objects by guessing at IDs.
3003
3004       Using ":SECURE" mode requires Math::Random::MT::Auto (v5.04 or later).
3005
3006       Because the object IDs used with ":SECURE" mode are large random
3007       values, the :HASH_ONLY flag is forced on all the classes in the
3008       hierarchy.
3009
3010       For efficiency, it is recommended that the ":SECURE" flag be added to
3011       the topmost class(es) in a hierarchy.
3012

ATTRIBUTE HANDLERS

3014       Object::InsideOut uses attribute 'modify' handlers as described in
3015       "Package-specific Attribute Handling" in attributes, and provides a
3016       mechanism for adding attribute handlers to your own classes.  Instead
3017       of naming your attribute handler as "MODIFY_*_ATTRIBUTES", name it
3018       something else and then label it with the ":MODIFY_*_ATTRIBUTES"
3019       attribute (or ":MOD_*_ATTRS" for short).  Your handler should work just
3020       as described in "Package-specific Attribute Handling" in attributes
3021       with regard to its input arguments, and must return a list of the
3022       attributes which were not recognized by your handler.  Here's an
3023       example:
3024
3025        package My::Class; {
3026            use Object::InsideOut;
3027
3028            sub _scalar_attrs :MOD_SCALAR_ATTRS
3029            {
3030                my ($pkg, $scalar, @attrs) = @_;
3031                my @unused_attrs;         # List of any unhandled attributes
3032
3033                while (my $attr = shift(@attrs)) {
3034                    if ($attr =~ /.../) {
3035                        # Handle attribute
3036                        ...
3037                    } else {
3038                        # We don't handle this attribute
3039                        push(@unused_attrs, $attr);
3040                    }
3041                }
3042
3043                return (@unused_attrs);   # Pass along unhandled attributes
3044            }
3045        }
3046
3047       Attribute 'modify' handlers are called upward through the class
3048       hierarchy (i.e., bottom up).  This provides child classes with the
3049       capability to override the handling of attributes by parent classes, or
3050       to add attributes (via the returned list of unhandled attributes) for
3051       parent classes to process.
3052
3053       Attribute 'modify' handlers should be located at the beginning of a
3054       package, or at least before any use of attributes on the corresponding
3055       type of variable or subroutine:
3056
3057        package My::Class; {
3058            use Object::InsideOut;
3059
3060            sub _array_attrs :MOD_ARRAY_ATTRS
3061            {
3062               ...
3063            }
3064
3065            my @my_array :MyArrayAttr;
3066        }
3067
3068       For attribute 'fetch' handlers, follow the same procedures:  Label the
3069       subroutine with the ":FETCH_*_ATTRIBUTES" attribute (or
3070       ":FETCH_*_ATTRS" for short).  Contrary to the documentation in
3071       "Package-specific Attribute Handling" in attributes, attribute 'fetch'
3072       handlers receive two arguments: The relevant package name, and a
3073       reference to a variable or subroutine for which package-defined
3074       attributes are desired.
3075
3076       Attribute handlers are normal rendered hidden.
3077

SPECIAL USAGE

3079   Usage With "Exporter"
3080       It is possible to use Exporter to export functions from one inside-out
3081       object class to another:
3082
3083        use strict;
3084        use warnings;
3085
3086        package Foo; {
3087            use Object::InsideOut 'Exporter';
3088            BEGIN {
3089                our @EXPORT_OK = qw(foo_name);
3090            }
3091
3092            sub foo_name
3093            {
3094                return (__PACKAGE__);
3095            }
3096        }
3097
3098        package Bar; {
3099            use Object::InsideOut 'Foo' => [ qw(foo_name) ];
3100
3101            sub get_foo_name
3102            {
3103                return (foo_name());
3104            }
3105        }
3106
3107        package main;
3108
3109        print("Bar got Foo's name as '", Bar::get_foo_name(), "'\n");
3110
3111       Note that the "BEGIN" block is needed to ensure that the Exporter
3112       symbol arrays (in this case @EXPORT_OK) get populated properly.
3113
3114   Usage With "require" and "mod_perl"
3115       Object::InsideOut usage under mod_perl and with runtime-loaded classes
3116       is supported automatically; no special coding is required.
3117
3118       Caveat: Runtime loading of classes should be performed before any
3119       objects are created within any of the classes in their hierarchies.  If
3120       Object::InsideOut cannot create a hierarchy because of previously
3121       created objects (even if all those objects have been destroyed), a
3122       runtime error will be generated.
3123
3124   Singleton Classes
3125       A singleton class is a case where you would provide your own "->new()"
3126       method that in turn calls Object::InsideOut's "->new()" method:
3127
3128        package My::Class; {
3129            use Object::InsideOut;
3130
3131            my $singleton;
3132
3133            sub new {
3134                my $thing = shift;
3135                if (! $singleton) {
3136                    $singleton = $thing->Object::InsideOut::new(@_);
3137                }
3138                return ($singleton);
3139            }
3140        }
3141

DIAGNOSTICS

3143       Object::InsideOut uses "Exception::Class" for reporting errors.  The
3144       base error class for this module is "OIO".  Here is an example of the
3145       basic manner for trapping and handling errors:
3146
3147        my $obj;
3148        eval { $obj = My::Class->new(); };
3149        if (my $e = OIO->caught()) {
3150            warn('Failure creating object: '.$e);
3151            ...
3152        }
3153
3154       A more comprehensive approach might employ elements of the following:
3155
3156        eval { ... };
3157        if (my $e = OIO->caught()) {
3158            # An error generated by Object::InsideOut
3159            ...
3160        } elsif (my $e = Exception::Class::Base->caught()) {
3161            # An error generated by other code that uses Exception::Class
3162            ...
3163        } elsif ($@) {
3164            # An unhandled error (i.e., generated by code that doesn't use
3165            # Exception::Class)
3166            ...
3167        }
3168
3169       I have tried to make the messages and information returned by the error
3170       objects as informative as possible.  Suggested improvements are
3171       welcome.  Also, please bring to my attention any conditions that you
3172       encounter where an error occurs as a result of Object::InsideOut code
3173       that doesn't generate an Exception::Class object.  Here is one such
3174       error:
3175
3176       Invalid ARRAY/HASH attribute
3177           This error indicates you forgot "use Object::InsideOut;" in your
3178           class's code.
3179
3180       Object::InsideOut installs a "__DIE__" handler (see "die LIST" in
3181       perlfunc and "eval BLOCK" in perlfunc) to catch any errant exceptions
3182       from class-specific code, namely, ":Init", ":Replicate", ":Destroy",
3183       etc.  subroutines.  When using "eval" blocks inside these subroutines,
3184       you should localize $SIG{'__DIE__'} to keep Object::InsideOut's
3185       "__DIE__" handler from interfering with exceptions generated inside the
3186       "eval" blocks.  For example:
3187
3188        sub _init :Init {
3189            ...
3190            eval {
3191                local $SIG{'__DIE__'};
3192                ...
3193            };
3194            if $@ {
3195                # Handle caught exception
3196            }
3197            ...
3198        }
3199
3200       Here's another example, where the "die" function is used as a method of
3201       flow control for leaving an "eval" block:
3202
3203        eval {
3204            local $SIG{'__DIE__'};           # Suppress any existing __DIE__ handler
3205            ...
3206            die({'found' => 1}) if $found;   # Leave the eval block
3207            ...
3208        };
3209        if ($@) {
3210            die unless (ref($@) && $@->{'found'});   # Propagate any 'real' error
3211            # Handle 'found' case
3212            ...
3213        }
3214        # Handle 'not found' case
3215
3216       Similarly, if calling code from other modules that use the above flow
3217       control mechanism, but without localizing $SIG{'__DIE__'}, you can
3218       workaround this deficiency with your own "eval" block:
3219
3220        eval {
3221            local $SIG{'__DIE__'};     # Suppress any existing __DIE__ handler
3222            Some::Module::func();      # Call function that fails to localize
3223        };
3224        if ($@) {
3225            # Handle caught exception
3226        }
3227
3228       In addition, you should file a bug report against the offending module
3229       along with a patch that adds the missing "local $SIG{'__DIE__'};"
3230       statement.
3231

BUGS AND LIMITATIONS

3233       If you receive an error similar to this:
3234
3235        ERROR: Attempt to DESTROY object ID 1 of class Foo twice
3236
3237       the cause may be that some module used by your application is doing
3238       "require threads" somewhere in the background.  DBI is one such module.
3239       The workaround is to add "use threads;" at the start of your
3240       application.
3241
3242       Another cause of the above is returning a non-shared object from a
3243       thread either explicitly or implicitly when the result of the last
3244       statement in the thread subroutine is an object.  For example:
3245
3246        sub thr_func {
3247            my $obj = MyClass->new();
3248        }
3249
3250       which is equivalent to:
3251
3252        sub thr_func {
3253            return MyClass->new();
3254        }
3255
3256       This can be avoided by ensuring your thread subroutine ends with
3257       "return;".
3258
3259       The equality operator (e.g., "if ($obj1 == $obj2) { ...") is overloaded
3260       for ":SHARED" classes when threads::shared is loaded.  The overload
3261       subroutine compares object classes and IDs because references to the
3262       same thread shared object may have different refaddrs.
3263
3264       You cannot overload an object to a scalar context (i.e., can't
3265       ":SCALARIFY").
3266
3267       You cannot use two instances of the same class with mixed thread object
3268       sharing in same application.
3269
3270       Cannot use attributes on subroutine stubs (i.e., forward declaration
3271       without later definition) with ":Automethod":
3272
3273        package My::Class; {
3274            sub method :Private;   # Will not work
3275
3276            sub _automethod :Automethod
3277            {
3278                # Code to handle call to 'method' stub
3279            }
3280        }
3281
3282       Due to limitations in the Perl parser, the entirety of any one
3283       attribute must be on a single line.  (However, multiple attributes may
3284       appear on separate lines.)
3285
3286       If a set accessor accepts scalars, then you can store any inside-out
3287       object type in it.  If its "Type" is set to "HASH", then it can store
3288       any blessed hash object.
3289
3290       Returning objects from threads does not work:
3291
3292        my $obj = threads->create(sub { return (Foo->new()); })->join();  # BAD
3293
3294       Instead, use thread object sharing, create the object before launching
3295       the thread, and then manipulate the object inside the thread:
3296
3297        my $obj = Foo->new();   # Class 'Foo' is set ':SHARED'
3298        threads->create(sub { $obj->set_data('bar'); })->join();
3299        my $data = $obj->get_data();
3300
3301       Due to a limitation in threads::shared version 1.39 and earlier, if
3302       storing shared objects inside other shared objects, you should use
3303       "delete()" to remove them from internal fields (e.g.,
3304       "delete($field[$$self]);") when necessary so that the objects'
3305       destructor gets called.  Upgrading to version 1.40 or later alleviates
3306       most of this issue except during global destruction.  See
3307       threads::shared for more.
3308
3309       With Perl 5.8.8 and earlier, there are bugs associated with
3310       threads::shared that may prevent you from storing objects inside of
3311       shared objects, or using foreign inheritance with shared objects.  With
3312       Perl 5.8.9 (and later) together with threads::shared 1.15 (and later),
3313       you can store shared objects inside of other shared objects, and you
3314       can use foreign inheritance with shared objects (provided the foreign
3315       class supports shared objects as well).
3316
3317       Due to internal complexities, the following actions are not supported
3318       in code that uses threads::shared while there are any threads active:
3319
3320       ·   Runtime loading of Object::InsideOut classes
3321
3322       ·   Using ->add_class()
3323
3324       It is recommended that such activities, if needed, be performed in the
3325       main application code before any threads are created (or at least while
3326       there are no active threads).
3327
3328       For Perl 5.6.0 through 5.8.0, a Perl bug prevents package variables
3329       (e.g., object attribute arrays/hashes) from being referenced properly
3330       from subroutine refs returned by an ":Automethod" subroutine.  For Perl
3331       5.8.0 there is no workaround:  This bug causes Perl to core dump.  For
3332       Perl 5.6.0 through 5.6.2, the workaround is to create a ref to the
3333       required variable inside the ":Automethod" subroutine, and use that
3334       inside the subroutine ref:
3335
3336        package My::Class; {
3337            use Object::InsideOut;
3338
3339            my %data;
3340
3341            sub auto :Automethod
3342            {
3343                my $self = $_[0];
3344                my $name = $_;
3345
3346                my $data = \%data;      # Workaround for 5.6.X bug
3347
3348                return sub {
3349                            my $self = shift;
3350                            if (! @_) {
3351                                return ($$data{$name});
3352                            }
3353                            $$data{$name} = shift;
3354                       };
3355            }
3356        }
3357
3358       For Perl 5.8.1 through 5.8.4, a Perl bug produces spurious warning
3359       messages when threads are destroyed.  These messages are innocuous, and
3360       can be suppressed by adding the following to your application code:
3361
3362        $SIG{'__WARN__'} = sub {
3363                if ($_[0] !~ /^Attempt to free unreferenced scalar/) {
3364                    print(STDERR @_);
3365                }
3366            };
3367
3368       A better solution would be to upgrade threads and threads::shared from
3369       CPAN, especially if you encounter other problems associated with
3370       threads.
3371
3372       For Perl 5.8.4 and 5.8.5, the "Storable" feature does not work due to a
3373       Perl bug.  Use Object::InsideOut v1.33 if needed.
3374
3375       Due to bugs in the Perl interpreter, using the introspection API (i.e.
3376       "->meta()", etc.) requires Perl 5.8.0 or later.
3377
3378       The version of Want that is available via PPM for ActivePerl is
3379       defective, and causes failures when using ":lvalue" accessors.  Remove
3380       it, and then download and install the Want module using CPAN.
3381
3382       Devel::StackTrace (used by Exception::Class) makes use of the DB
3383       namespace.  As a consequence, Object::InsideOut thinks that
3384       "package DB" is already loaded.  Therefore, if you create a class
3385       called DB that is sub-classed by other packages, you may need to
3386       "require" it as follows:
3387
3388        package DB::Sub; {
3389            require DB;
3390            use Object::InsideOut qw(DB);
3391            ...
3392        }
3393
3394       View existing bug reports at, and submit any new bugs, problems,
3395       patches, etc.  to:
3396       <http://rt.cpan.org/Public/Dist/Display.html?Name=Object-InsideOut>
3397

REQUIREMENTS

3399       Perl 5.6.0 or later
3400       Exception::Class v1.22 or later
3401       Scalar::Util v1.10 or later
3402           It is possible to install a pure perl version of Scalar::Util,
3403           however, it will be missing the weaken() function which is needed
3404           by Object::InsideOut.  You'll need to upgrade your version of
3405           Scalar::Util to one that supports its "XS" code.
3406
3407       Test::More v0.50 or later
3408           Needed for testing during installation.
3409
3410       Want v0.12 or later
3411           Optional.  Provides support for ":lvalue Accessors".
3412
3413       Math::Random::MT::Auto v5.04 or later)
3414           Optional.  Provides support for :SECURE mode.
3415
3416       To cover all of the above requirements and more, it is recommended that
3417       you install Bundle::Object::InsideOut using CPAN:
3418
3419        perl -MCPAN -e 'install Bundle::Object::InsideOut'
3420
3421       This will install the latest versions of all the required and optional
3422       modules needed for full support of all of the features provided by
3423       Object::InsideOut.
3424

SEE ALSO

3426       Object::InsideOut on MetaCPAN:
3427       <https://metacpan.org/release/Object-InsideOut>
3428
3429       Code repository: <https://github.com/jdhedden/Object-InsideOut>
3430
3431       Inside-out Object Model:
3432       <http://www.perlfoundation.org/perl5/index.cgi?inside_out_object>,
3433       <http://www.perlmonks.org/?node_id=219378>,
3434       <http://www.perlmonks.org/?node_id=483162>,
3435       <http://www.perlmonks.org/?node_id=515650>, Chapters 15 and 16 of Perl
3436       Best Practices by Damian Conway
3437
3438       Object::InsideOut::Metadata
3439
3440       Storable, <Exception:Class>, Want, Math::Random::MT::Auto, attributes,
3441       overload
3442
3443       Sample code in the examples directory of this distribution on CPAN.
3444

ACKNOWLEDGEMENTS

3446       Abigail <perl AT abigail DOT nl> for inside-out objects in general.
3447
3448       Damian Conway <dconway AT cpan DOT org> for Class::Std, and for
3449       delegator methods.
3450
3451       David A. Golden <dagolden AT cpan DOT org> for thread handling for
3452       inside-out objects.
3453
3454       Dan Kubb <dan.kubb-cpan AT autopilotmarketing DOT com> for ":Chained"
3455       methods.
3456

AUTHOR

3458       Jerry D. Hedden, <jdhedden AT cpan DOT org>
3459
3461       Copyright 2005 - 2012 Jerry D. Hedden. All rights reserved.
3462
3463       This program is free software; you can redistribute it and/or modify it
3464       under the same terms as Perl itself.
3465

TRANSLATIONS

3467       A Japanese translation of this documentation by TSUJII, Naofumi
3468       <tsun DOT nt AT gmail DOT com> is available at
3469       <http://perldoc.jp/docs/modules/>.
3470
3471
3472
3473perl v5.30.0                      2019-07-26              Object::InsideOut(3)
Impressum