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

NAME

6       "Object::Pad" - a simple syntax for lexical field-based objects
7

SYNOPSIS

9       On perl version 5.26 onwards:
10
11          use v5.26;
12          use Object::Pad;
13
14          class Point {
15             has $x :param = 0;
16             has $y :param = 0;
17
18             method move ($dX, $dY) {
19                $x += $dX;
20                $y += $dY;
21             }
22
23             method describe () {
24                print "A point at ($x, $y)\n";
25             }
26          }
27
28          Point->new(x => 5, y => 10)->describe;
29
30       Or, for older perls that lack signatures:
31
32          use Object::Pad;
33
34          class Point {
35             has $x :param = 0;
36             has $y :param = 0;
37
38             method move {
39                my ($dX, $dY) = @_;
40                $x += $dX;
41                $y += $dY;
42             }
43
44             method describe {
45                print "A point at ($x, $y)\n";
46             }
47          }
48
49          Point->new(x => 5, y => 10)->describe;
50

DESCRIPTION

52       This module provides a simple syntax for creating object classes, which
53       uses private variables that look like lexicals as object member fields.
54
55       WARNING This module is still experimental. The parts that currently
56       exist do seem to work reliably but much of the design is still
57       evolving, and many features and have yet to be implemented. I don't yet
58       guarantee I won't have to change existing details in order to continue
59       its development. Feel free to try it out in experimental or newly-
60       developed code, but don't complain if a later version is incompatible
61       with your current code and you'll have to change it.
62
63       That all said, please do get in contact if you find the module overall
64       useful.  The more feedback you provide in terms of what features you
65       are using, what you find works, and what doesn't, will help the ongoing
66       development and hopefully eventual stability of the design. See the
67       "FEEDBACK" section.
68
69   Automatic Construction
70       Classes are automatically provided with a constructor method, called
71       "new", which helps create the object instances. This may respond to
72       passed arguments, automatically assigning values of fields, and
73       invoking other blocks of code provided by the class. It proceeds in the
74       following stages:
75
76       The BUILDARGS phase
77
78       If the class provides a "BUILDARGS" class method, that is used to
79       mangle the list of arguments before the "BUILD" blocks are called. Note
80       this must be a class method not an instance method (and so implemented
81       using "sub"). It should perform any "SUPER" chaining as may be
82       required.
83
84          @args = $class->BUILDARGS( @_ )
85
86       Field assignment
87
88       If any field in the class has the ":param" attribute, then the
89       constructor will expect to receive its argmuents in an even-sized list
90       of name/value pairs. This applies even to fields inherited from the
91       parent class or applied roles. It is therefore a good idea to shape the
92       parameters to the constructor in this way in roles, and in classes if
93       you intend your class to be extended.
94
95       The constructor will also check for required parameters (these are all
96       the parameters for fields that do not have default initialisation
97       expressions). If any of these are missing an exception is thrown.
98
99       The BUILD phase
100
101       As part of the construction process, the "BUILD" block of every
102       component class will be invoked, passing in the list of arguments the
103       constructor was invoked with. Each class should perform its required
104       setup behaviour, but does not need to chain to the "SUPER" class first;
105       this is handled automatically.
106
107       The ADJUST phase
108
109       Next, the "ADJUST" and "ADJUSTPARAMS" block of every component class is
110       invoked. This happens after the fields are assigned their initial
111       values and the "BUILD" blocks have been run.
112
113       Note also that both "ADJUST" and "ADJUSTPARAMS" blocks happen at the
114       same time, in declaration order. The "ADJUSTPARAMS" blocks do not form
115       their own separate phase.
116
117       The strict-checking phase
118
119       Finally, before the object is returned, if the ":strict(params)" class
120       attribute is present, then the constructor will throw an exception if
121       there are any remaining named arguments left over after assigning them
122       to fields as per ":param" declarations, and running any "ADJUSTPARAMS"
123       blocks.
124

KEYWORDS

126   class
127          class Name :ATTRS... {
128             ...
129          }
130
131          class Name :ATTRS...;
132
133       Behaves similarly to the "package" keyword, but provides a package that
134       defines a new class. Such a class provides an automatic constructor
135       method called "new".
136
137       As with "package", an optional block may be provided. If so, the
138       contents of that block define the new class and the preceding package
139       continues afterwards. If not, it sets the class as the package context
140       of following keywords and definitions.
141
142       As with "package", an optional version declaration may be given. If so,
143       this sets the value of the package's $VERSION variable.
144
145          class Name VERSION { ... }
146
147          class Name VERSION;
148
149       A single superclass is supported by the keyword "isa"
150
151       Since version 0.41.
152
153          class Name isa BASECLASS {
154             ...
155          }
156
157          class Name isa BASECLASS BASEVER {
158             ...
159          }
160
161       Prior to version 0.41 this was called "extends", which is currently
162       recognised as a compatibility synonym. Both "extends" and "isa"
163       keywords are now discouraged, in favour of the ":isa" attribute which
164       is preferred because it follows a more standard grammar without this
165       special-case.
166
167       One or more roles can be composed into the class by the keyword "does"
168
169       Since version 0.41.
170
171          class Name does ROLE, ROLE,... {
172             ...
173          }
174
175       Prior to version 0.41 this was called "implements", which is currently
176       recognised as a compatibility synonym. Both "implements" and "does"
177       keywords are now discouraged, in favour of the ":does" attribute which
178       is preferred because it follows a more standard grammar without this
179       special-case.
180
181       An optional list of attributes may be supplied in similar syntax as for
182       subs or lexical variables. (These are annotations about the class
183       itself; the concept should not be confused with per-object-instance
184       data, which here is called "fields").
185
186       Whitespace is permitted within the value and is automatically trimmed,
187       but as standard Perl parsing rules, no space is permitted between the
188       attribute's name and the open parenthesis of its value:
189
190          :attr( value here )     # is permitted
191          :attr (value here)      # not permitted
192
193       The following class attributes are supported:
194
195       :isa
196
197          :isa(CLASS)
198
199          :isa(CLASS CLASSVER)
200
201       Since version 0.57.
202
203       Declares a superclass that this class extends. At most one superclass
204       is supported.
205
206       If the package providing the superclass does not exist, an attempt is
207       made to load it by code equivalent to
208
209          require CLASS ();
210
211       and thus it must either already exist, or be locatable via the usual
212       @INC mechanisms.
213
214       The superclass may or may not itself be implemented by "Object::Pad",
215       but if it is not then see "SUBCLASSING CLASSIC PERL CLASSES" for
216       further detail on the semantics of how this operates.
217
218       An optional version check can also be supplied; it performs the
219       equivalent of
220
221          BaseClass->VERSION( $ver )
222
223       :does
224
225          :does(ROLE)
226
227          :does(ROLE ROLEVER)
228
229       Since version 0.57.
230
231       Composes a role into the class; optionally requiring a version check on
232       the role package. This is a newer form of the "implements" and "does"
233       keywords and should be preferred for new code.
234
235       Multiple roles can be composed by using multiple ":does" attributes,
236       one per role.
237
238       The package will be loaded in a similar way to how the ":isa" attribute
239       is handled.
240
241       :repr(TYPE)
242
243       Sets the representation type for instances of this class. Must be one
244       of the following values:
245
246          :repr(native)
247
248       The native representation. This is an opaque representation type whose
249       contents are not specified. It only works for classes whose entire
250       inheritence hierarchy is built only from classes based on
251       "Object::Pad".
252
253          :repr(HASH)
254
255       The representation will be a blessed hash reference. The instance data
256       will be stored in an array referenced by a key called
257       "Object::Pad/slots", which is fairly unlikely to clash with existing
258       storage on the instance. No other keys will be used; they are available
259       for implementions and subclasses to use.  The exact format of the value
260       stored here is not specified and may change between module versions,
261       though it can be relied on to be well-behaved as some kind of perl data
262       structure for purposes of modules like Data::Dumper or serialisation
263       into things like "YAML" or "JSON".
264
265       This representation type may be useful when converting existing classes
266       into using "Object::Pad" where there may be existing subclasses of it
267       that presume a blessed hash for their own use.
268
269          :repr(magic)
270
271       The representation will use MAGIC to apply the instance data in a way
272       that is invisible at the Perl level, and shouldn't get in the way of
273       other things the instance is doing even in XS modules.
274
275       This representation type is the only one that will work for subclassing
276       existing classes that do not use blessed hashes.
277
278          :repr(autoselect), :repr(default)
279
280       Since version 0.23.
281
282       This representation will select one of the representations above
283       depending on what is best for the situation. Classes not derived from a
284       non-"Object::Pad" base class will pick "native", and classes derived
285       from non-"Object::Pad" bases will pick either the "HASH" or "magic"
286       forms depending on whether the instance is a blessed hash reference or
287       some other kind.
288
289       This achieves the best combination of DWIM while still allowing the
290       common forms of hash reference to be inspected by "Data::Dumper", etc.
291       This is the default representation type, and does not have to be
292       specifically requested.
293
294       :strict(params)
295
296       Since version 0.43.
297
298       Can only be applied to classes that contain no "BUILD" blocks. If set,
299       then the constructor will complain about any unrecognised named
300       arguments passed to it (i.e. names that do not correspond to the
301       ":param" of any defined field and left unconsumed by any "ADJUSTPARAMS"
302       block).
303
304       Since "BUILD" blocks can inspect the arguments arbitrarily, the
305       presence of any such block means the constructor cannot determine which
306       named arguments are not recognised.
307
308       This attribute is a temporary stepping-stone for compatibility with
309       existing code. It is recommended to enable this whenever possible, as a
310       later version of this module will likely perform this behaviour
311       unconditionally whenever no "BUILD" blocks are present.
312
313   role
314          role Name :ATTRS... {
315             ...
316          }
317
318          role Name :ATTRS...;
319
320       Since version 0.32.
321
322       Similar to "class", but provides a package that defines a new role. A
323       role acts simliar to a class in some respects, and differently in
324       others.
325
326       Like a class, a role can have a version, and named methods.
327
328          role Name VERSION {
329             method a { ... }
330             method b { ... }
331          }
332
333       A role does not provide a constructor, and instances cannot directly be
334       constructed. A role cannot extend a class.
335
336       A role can declare that it requires methods of given names from any
337       class that implements the role.
338
339          role Name {
340             requires METHOD;
341          }
342
343       A role can provide instance fields. These are visible to any "BUILD"
344       blocks or methods provided by that role.
345
346       Since version 0.33.
347
348          role Name {
349             has $field;
350
351             BUILD { $field = "a value" }
352
353             method field { return $field }
354          }
355
356       Since version 0.57 a role can declare that it provides another role:
357
358          role Name :does(OTHERROLE) { ... }
359          role Name :does(OTHERROLE OTHERVER) { ... }
360
361       This will include all of the methods from the included role.
362       Effectively this means that applying the "outer" role to a class will
363       imply applying the other role as well.
364
365       The following role attributes are supported:
366
367       :compat(invokable)
368
369       Since version 0.35.
370
371       Enables a form of backward-compatibility behaviour useful for gradually
372       upgrading existing code from classical Perl inheritance or mixins into
373       using roles.
374
375       Normally, methods of a role cannot be directly invoked and the role
376       must be applied to an Object::Pad-based class in order to be used. This
377       however presents a problem when gradually upgrading existing code that
378       already uses techniques like roles, multiple inheritance or mixins when
379       that code may be split across multiple distributions, or for some other
380       reason cannot be upgraded all at once. Methods within a role that has
381       the ":compat(invokable)" attribute applied to it may be directly
382       invoked on any object instance. This allows the creation of a role that
383       can still provide code for existing classes written in classical Perl
384       that has not yet been rewritten to use "Object::Pad".
385
386       The tradeoff is that a ":compat(invokable)" role may not create field
387       data using the "has" keyword. Whatever behaviours the role wishes to
388       perform must be provided only by calling other methods on $self, or
389       perhaps by making assumptions about the representation type of
390       instances.
391
392       It should be stressed again: This option is only intended for gradual
393       upgrade of existing classical Perl code into using "Object::Pad". When
394       all existing code is using "Object::Pad" then this attribute can be
395       removed from the role.
396
397   has
398          has $var;
399          has @var;
400          has %var;
401
402          has $var :ATTR ATTR...;
403
404          has $var = EXPR;
405
406          has $var { BLOCK }
407
408       Declares that the instances of the class or role have a member field of
409       the given name. This member field will be accessible as a lexical
410       variable within any "method" declarations in the class.
411
412       Array and hash members are permitted and behave as expected; you do not
413       need to store references to anonymous arrays or hashes.
414
415       Member fields are private to a class or role. They are not visible to
416       users of the class, nor inherited by subclasses nor any class that a
417       role is applied to. In order to provide access to them a class may wish
418       to use "method" to create an accessor, or use the attributes such as
419       ":reader" to get one generated.
420
421       A scalar field may provide a expression that gives an initialisation
422       value, which will be assigned into the field of every instance during
423       the constructor before the "BUILD" blocks are invoked. Since version
424       0.29 this expression does not have to be a compiletime constant, though
425       it is evaluated exactly once, at runtime, after the class definition
426       has been parsed. It is not evaluated individually for every object
427       instance of that class. Since version 0.54 this is also permitted on
428       array and hash fields.
429
430       Field Initialiser Blocks
431
432       Since version 0.54 a deferred statement block is also permitted, on any
433       field variable type. This is an experimental feature that permits code
434       to be executed as part of the instance constructor, rather than running
435       just once when the class is set up. Code in a field initialisation
436       block is roughly equivalent to being placed in a "BUILD" or "ADJUST"
437       block.
438
439       Control flow that attempts to leave a field initialiser block is not
440       permitted. This includes any "return" expression, any "next/last/redo"
441       outside of a loop, with a dynamically-calculated label expression, or
442       with a label that it doesn't appear in. "goto" statements are also
443       currently forbidden, though known-safe ones may be permitted in future.
444
445       Loop control expressions that are known at compiletime to affect a loop
446       that they appear within are permitted.
447
448          has $field { foreach(@list) { next; } }       # this is fine
449
450          has $field { LOOP: while(1) { last LOOP; } }  # this is fine too
451
452       The following field attributes are supported:
453
454       :reader, :reader(NAME)
455
456       Since version 0.27.
457
458       Generates a reader method to return the current value of the field. If
459       no name is given, the name of the field is used. A single prefix
460       character "_" will be removed if present.
461
462          has $field :reader;
463
464          # equivalent to
465          has $field;  method field { return $field }
466
467       Since version 0.55 these are permitted on any field type, but prior
468       versions only allowed them on scalar fields. The reader method behaves
469       identically to how a lexical variable would behave in the same context;
470       namely returning a list of values from an array or key/value pairs from
471       a hash when in list context, or the number of items or keys when in
472       scalar context.
473
474          has @items :reader;
475
476          foreach my $item ( $obj->items ) { ... }   # iterates the list of items
477
478          my $count = $obj->items;                   # yields count of items
479
480       :writer, :writer(NAME)
481
482       Since version 0.27.
483
484       Generates a writer method to set a new value of the field from its
485       arguments.  If no name is given, the name of the field is used prefixed
486       by "set_". A single prefix character "_" will be removed if present.
487
488          has $field :writer;
489
490          # equivalent to
491          has $field;  method set_field { $field = shift; return $self }
492
493       Since version 0.28 a generated writer method will return the object
494       invocant itself, allowing a chaining style.
495
496          $obj->set_x("x")
497             ->set_y("y")
498             ->set_z("z");
499
500       Since version 0.55 these are permitted on any field type, but prior
501       versions only allowed them on scalar fields. On arrays or hashes, the
502       writer method takes a list of values to be assigned into the field,
503       completely replacing any values previously there.
504
505       :mutator, :mutator(NAME)
506
507       Since version 0.27.
508
509       Generates an lvalue mutator method to return or set the value of the
510       field.  These are only permitted for scalar fields. If no name is
511       given, the name of the field is used. A single prefix character "_"
512       will be removed if present.
513
514          has $field :mutator;
515
516          # equivalent to
517          has $field;  method field :lvalue { $field }
518
519       Since version 0.28 all of these generated accessor methods will include
520       argument checking similar to that used by subroutine signatures, to
521       ensure the correct number of arguments are passed - usually zero, but
522       exactly one in the case of a ":writer" method.
523
524       :accessor, :accessor(NAME)
525
526       Since version 0.53.
527
528       Generates a combined reader-writer accessor method to set or return the
529       value of the field. These are only permitted for scalar fields. If no
530       name is given, the name of the field is used. A prefix character "_"
531       will be removed if present.
532
533       This method takes either zero or one additional arguments. If an
534       argument is passed, the value of the field is set from this argument
535       (even if it is "undef"). If no argument is passed (i.e. "scalar @_" is
536       false) then the field is not modified. In either case, the value of the
537       field is then returned.
538
539          has $field :accessor;
540
541          # equivalent to
542          has $field;
543
544          method field {
545             $field = shift if @_;
546             return $field;
547          }
548
549       :weak
550
551       Since version 0.44.
552
553       Generated code which sets the value of this field will weaken it if it
554       contains a reference. This applies to within the constructor if
555       ":param" is given, and to a ":writer" accessor method. Note that this
556       only applies to automatically generated code; not normal code written
557       in regular method bodies. If you assign into the field variable you
558       must remember to call "Scalar::Util::weaken" yourself.
559
560       :param, :param(NAME)
561
562       Since version 0.41.
563
564       Sets this field to be initialised automatically in the generated
565       constructor.  This is only permitted on scalar fields. If no name is
566       given, the name of the field is used. A single prefix character "_"
567       will be removed if present.
568
569       Any field that has ":param" but does not have a default initialisation
570       expression or block becomes a required argument to the constructor.
571       Attempting to invoke the constructor without a named argument for this
572       will throw an exception. In order to make a parameter optional, make
573       sure to give it a default expression - even if that expression is
574       "undef":
575
576          has $x :param;          # this is required
577          has $z :param = undef;  # this is optional
578
579       Any field that has a ":param" and an initialisation block will only run
580       the code in the block if required by the constructor. If a named
581       parameter is passed to the constructor for this field, then its code
582       block will not be executed.
583
584       Values for fields are assigned by the constructor before any "BUILD"
585       blocks are invoked.
586
587   method
588          method NAME {
589             ...
590          }
591
592          method NAME (SIGNATURE) {
593             ...
594          }
595
596          method NAME :ATTRS... {
597             ...
598          }
599
600          method NAME;
601
602       Declares a new named method. This behaves similarly to the "sub"
603       keyword, except that within the body of the method all of the member
604       fields are also accessible. In addition, the method body will have a
605       lexical called $self which contains the invocant object directly; it
606       will already have been shifted from the @_ array.
607
608       If the method has no body and is given simply as a name, this declares
609       a required method for a role. Such a method must be provided by any
610       class that implements the role. It will be a compiletime error to
611       combine the role with a class that does not provide this.
612
613       The "signatures" feature is automatically enabled for method
614       declarations. In this case the signature does not have to account for
615       the invocant instance; that is handled directly.
616
617          method m ($one, $two) {
618             say "$self invokes method on one=$one two=$two";
619          }
620
621          ...
622          $obj->m(1, 2);
623
624       A list of attributes may be supplied as for "sub". The most useful of
625       these is ":lvalue", allowing easy creation of read-write accessors for
626       fields (but see also the ":reader", ":writer" and ":mutator" field
627       attributes).
628
629          class Counter {
630             has $count;
631
632             method count :lvalue { $count }
633          }
634
635          my $c = Counter->new;
636          $c->count++;
637
638       Every method automatically gets the ":method" attribute applied, which
639       suppresses warnings about ambiguous calls resolved to core functions if
640       the name of a method matches a core function.
641
642       The following additional attributes are recognised by "Object::Pad"
643       directly:
644
645       :override
646
647       Since version 0.29.
648
649       Marks that this method expects to override another of the same name
650       from a superclass. It is an error at compiletime if the superclass does
651       not provide such a method.
652
653       :common
654
655       Since version 0.62.
656
657       Marks that this method is a class-common method, instead of a regular
658       instance method. A class-common method may be invoked on class names
659       instead of instances. Within the method body there is a lexical $class
660       available, rather than $self. Because it is not associated with a
661       particular object instance, a class-common method cannot see instance
662       fields.
663
664   method (lexical)
665          method $var { ... }
666
667          method $var :ATTRS... (SIGNATURE) { ... }
668
669       Since version 0.59.
670
671       Declares a new lexical method. Lexical methods are not visible via the
672       package namespace, but instead are stored directly in a lexical
673       variable (with the same scoping rules as regular "my" variables). These
674       can be invoked by subsequent method code in the same block by using
675       "$self->$var(...)"  method call syntax.
676
677          class WithPrivate {
678             has $var;
679
680             # Lexical methods can still see instance fields as normal
681             method $inc_var { $var++; say "Var was incremented"; }
682             method $dec_var { $var--; say "Var was decremented"; }
683
684             method bump {
685                $self->$inc_var;
686                say "In the middle";
687                $self->$dec_var;
688             }
689          }
690
691          my $obj = WithPrivate->new;
692
693          $obj->bump;
694
695          # Neither $inc_var nor $dec_var are visible here
696
697       This effectively provides the ability to define private methods, as
698       they are inaccessible from outside the block that defines the class. In
699       addition, there is no chance of a name collision because lexical
700       variables in different scopes are independent, even if they share the
701       same name. This is particularly useful in roles, to create internal
702       helper methods without letting those methods be visible to callers, or
703       risking their names colliding with other named methods defined on the
704       consuming class.
705
706   BUILD
707          BUILD {
708             ...
709          }
710
711          BUILD (SIGNATURE) {
712             ...
713          }
714
715       Since version 0.27.
716
717       Declares the builder block for this component class. A builder block
718       may use subroutine signature syntax, as for methods, to assist in
719       unpacking its arguments. A build block is not a subroutine and thus is
720       not permitted to use subroutine attributes (for example ":lvalue").
721
722       Note that a "BUILD" block is a named phaser block and not a method.
723       Attempts to create a method named "BUILD" (i.e. with syntax "method
724       BUILD {...}") will fail with a compiletime error, to avoid this
725       confusion.
726
727   ADJUST
728          ADJUST {
729             ...
730          }
731
732       Since version 0.43.
733
734       Declares an adjust block for this component class. This block of code
735       runs within the constructor, after any "BUILD" blocks and automatic
736       field value assignment. It can make any final adjustments to the
737       instance (such as initialising fields from calculated values). No
738       additional parameters are passed.
739
740       An adjust block is not a subroutine and thus is not permitted to use
741       subroutine attributes. Note that an "ADJUST" block is a named phaser
742       block and not a method; it does not use the "sub" or "method" keyword.
743
744   ADJUSTPARAMS
745          ADJUSTPARAMS ( $params ) {    # on perl 5.26 onwards
746             ...
747          }
748
749          ADJUSTPARAMS {
750             my $params = shift;
751             ...
752          }
753
754       Since version 0.51.
755
756       Declares an adjust block for this component class that receives the
757       parameters hash reference. This block of code runs within the
758       constructor at the same time as "ADJUST" blocks, but receives in
759       addition a reference to the hash containing the current constructor
760       parameters. This hash will not contain any constructor parameters
761       already consumed by ":param" declarations on any fields, but only the
762       leftovers once those are processed.
763
764       The code in the block should "delete" from this hash any parameters it
765       wishes to consume. Once all the "ADJUSTPARAMS" blocks have run, any
766       remaining keys in the hash will be considered errors, subject to the
767       ":strict(params)" check.
768
769   requires
770          requires NAME;
771
772       Declares that this role requires a method of the given name from any
773       class that implements it. It is an error at compiletime if the
774       implementing class does not provide such a method.
775
776       This form of declaring a required method is now vaguely discouraged, in
777       favour of the bodyless "method" form described above.
778

CREPT FEATURES

780       While not strictly part of being an object system, this module has
781       nevertheless gained a number of behaviours by feature creep, as they
782       have been found useful.
783
784   Implied Pragmata
785       In order to encourage users to write clean, modern code, the body of
786       the "class" block acts as if the following pragmata are in effect:
787
788          use strict;
789          use warnings;
790          no indirect ':fatal';  # or  no feature 'indirect' on perl 5.32 onwards
791          use feature 'signatures';
792
793       This list may be extended in subsequent versions to add further
794       restrictions and should not be considered exhaustive.
795
796       Further additions will only be ones that remove "discouraged" or
797       deprecated language features with the overall goal of enforcing a more
798       clean modern style within the body. As long as you write code that is
799       in a clean, modern style (and I fully accept that this wording is vague
800       and subjective) you should not find any new restrictions to be majorly
801       problematic. Either the code will continue to run unaffected, or you
802       may have to make some small alterations to bring it into a conforming
803       style.
804
805   Yield True
806       A "class" statement or block will yield a true boolean value. This
807       means that it can be used directly inside a .pm file, avoiding the need
808       to explicitly yield a true value from the end of it.
809

SUBCLASSING CLASSIC PERL CLASSES

811       There are a number of details specific to the case of deriving an
812       "Object::Pad" class from an existing classic Perl class that is not
813       implemented using "Object::Pad".
814
815   Storage of Instance Data
816       Instances will pick either the ":repr(HASH)" or ":repr(magic)" storage
817       type.
818
819   Object State During Methods Invoked By Superclass Constructor
820       It is common in classic Perl OO style to invoke methods on $self during
821       the constructor. This is supported here since "Object::Pad" version
822       0.19.  Note however that any methods invoked by the superclass
823       constructor may not see the object in a fully consistent state. (This
824       fact is not specific to using "Object::Pad" and would happen in classic
825       Perl OO as well). The field initialisers will have been invoked but the
826       "BUILD" blocks will not.
827
828       For example; in the following
829
830          package ClassicPerlBaseClass {
831             sub new {
832                my $self = bless {}, shift;
833                say "Value seen by superconstructor is ", $self->get_value;
834                return $self;
835             }
836             sub get_value { return "A" }
837          }
838
839          class DerivedClass :isa(ClassicPerlBaseClass) {
840             has $_value = "B";
841             BUILD {
842                $_value = "C";
843             }
844             method get_value { return $_value }
845          }
846
847          my $obj = DerivedClass->new;
848          say "Value seen by user is ", $obj->get_value;
849
850       Until the "ClassicPerlBaseClass::new" superconstructor has returned the
851       "BUILD" block will not have been invoked. The $_value field will still
852       exist, but its value will be "B" during the superconstructor. After the
853       superconstructor, the "BUILD" blocks are invoked before the completed
854       object is returned to the user. The result will therefore be:
855
856          Value seen by superconstructor is B
857          Value seen by user is C
858

STYLE SUGGESTIONS

860       While in no way required, the following suggestions of code style
861       should be noted in order to establish a set of best practices, and
862       encourage consistency of code which uses this module.
863
864   $VERSION declaration
865       While it would be nice for CPAN and other toolchain modules to parse
866       the embedded version declarations in "class" statements, the current
867       state at time of writing (June 2020) is that none of them actually do.
868       As such, it will still be necessary to make a once-per-file $VERSION
869       declaration in syntax those modules can parse.
870
871       Further note that these modules will also not parse the "class"
872       declaration, so you will have to duplicate this with a "package"
873       declaration as well as a "class" keyword. This does involve repeating
874       the package name, so is slightly undesirable.
875
876       It is hoped that eventually upstream toolchain modules will be adapted
877       to accept the "class" syntax as being sufficient to declare a package
878       and set its version.
879
880       See also
881
882       • <https://github.com/Perl-Toolchain-Gang/Module-Metadata/issues/33>
883
884   File Layout
885       Begin the file with a "use Object::Pad" line; ideally including a
886       minimum-required version. This should be followed by the toplevel
887       "package" and "class" declarations for the file. As it is at toplevel
888       there is no need to use the block notation; it can be a unit class.
889
890       There is no need to "use strict" or apply other usual pragmata; these
891       will be implied by the "class" keyword.
892
893          use Object::Pad 0.16;
894
895          package My::Classname 1.23;
896          class My::Classname;
897
898          # other use statements
899
900          # has, methods, etc.. can go here
901
902   Field Names
903       Field names should follow similar rules to regular lexical variables in
904       code - lowercase, name components separated by underscores. For tiny
905       examples such as "dumb record" structures this may be sufficient.
906
907          class Tag {
908             has $name  :mutator;
909             has $value :mutator;
910          }
911
912       In larger examples with lots of non-trivial method bodies, it can get
913       confusing to remember where the field variables come from (because we
914       no longer have the "$self->{ ... }" visual clue). In these cases it is
915       suggested to prefix the field names with a leading underscore, to make
916       them more visually distinct.
917
918          class Spudger {
919             has $_grapefruit;
920
921             ...
922
923             method mangle {
924                $_grapefruit->peel; # The leading underscore reminds us this is a field
925             }
926          }
927

WITH OTHER MODULES

929   Syntax::Keyword::Dynamically
930       A cross-module integration test asserts that "dynamically" works
931       correctly on object instance fields:
932
933          use Object::Pad;
934          use Syntax::Keyword::Dynamically;
935
936          class Container {
937             has $value = 1;
938
939             method example {
940                dynamically $value = 2;
941                ,..
942                # value is restored to 1 on return from this method
943             }
944          }
945
946   Future::AsyncAwait
947       As of Future::AsyncAwait version 0.38 and Object::Pad version 0.15,
948       both modules now use XS::Parse::Sublike to parse blocks of code.
949       Because of this the two modules can operate together and allow class
950       methods to be written as async subs which await expressions:
951
952          use Future::AsyncAwait;
953          use Object::Pad;
954
955          class Example
956          {
957             async method perform ($block)
958             {
959                say "$self is performing code";
960                await $block->();
961                say "code finished";
962             }
963          }
964
965       These three modules combine; there is additionally a cross-module test
966       to ensure that object instance fields can be "dynamically" set during a
967       suspended "async method".
968

DESIGN TODOs

970       The following points are details about the design of pad field-based
971       object systems in general:
972
973       •   Is multiple inheritence actually required, if role composition is
974           implemented including giving roles the ability to use private
975           fields?
976
977       •   Consider the visibility of superclass fields to subclasses. Do
978           subclasses even need to be able to see their superclass's fields,
979           or are accessor methods always appropriate?
980
981           Concrete example: The "$self->{split_at}" access that
982           Tickit::Widget::HSplit makes of its parent class
983           Tickit::Widget::LinearSplit.
984

IMPLEMENTATION TODOs

986       These points are more about this particular module's implementation:
987
988       •   Consider multiple inheritence of subclassing, if that is still
989           considered useful after adding roles.
990
991       •   Work out why "no indirect" doesn't appear to work properly before
992           perl 5.20.
993
994       •   Work out why we don't get a "Subroutine new redefined at ..."
995           warning if we
996
997             sub new { ... }
998
999       •   The "local" modifier does not work on field variables, because they
1000           appear to be regular lexicals to the parser at that point. A
1001           workaround is to use Syntax::Keyword::Dynamically instead:
1002
1003              use Syntax::Keyword::Dynamically;
1004
1005              has $loglevel;
1006
1007              method quietly {
1008                 dynamically $loglevel = LOG_ERROR;
1009                 ...
1010              }
1011

FEEDBACK

1013       The following resources are useful forms of providing feedback,
1014       especially in the form of reports of what you find good or bad about
1015       the module, requests for new features, questions on best practice,
1016       etc...
1017
1018       •   The RT queue at
1019           <https://rt.cpan.org/Dist/Display.html?Name=Object-Pad>.
1020
1021       •   The "#cor" IRC channel on "irc.perl.org".
1022

SPONSORS

1024       With thanks to the following sponsors, who have helped me be able to
1025       spend time working on this module and other perl features.
1026
1027       •   Oetiker+Partner AG <https://www.oetiker.ch/en/>
1028
1029       •   Deriv <http://deriv.com>
1030
1031       •   Perl-Verein Schweiz <https://www.perl-workshop.ch/>
1032
1033       Additional details may be found at
1034       <https://github.com/Ovid/Cor/wiki/Sponsors>.
1035

AUTHOR

1037       Paul Evans <leonerd@leonerd.org.uk>
1038
1039
1040
1041perl v5.34.0                      2022-03-02                    Object::Pad(3)
Impressum