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       While most of this module has evolved into a stable state in practice,
56       parts remain experimental because the design is still evolving, and
57       many features and ideas have yet to implemented. I don't yet guarantee
58       I won't have to change existing details in order to continue its
59       development. Feel free to try it out in experimental or newly-developed
60       code, but don't complain if a later version is incompatible with your
61       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   Experimental Features
70       Since version 0.63.
71
72       Some of the features of this module are currently marked as
73       experimental. They will provoke warnings in the "experimental"
74       category, unless silenced.
75
76       You can silence this with "no warnings 'experimental'" but then that
77       will silence every experimental warning, which may hide others
78       unintentionally. For a more fine-grained approach you can instead use
79       the import line for this module to only silence the module's warnings
80       selectively:
81
82          use Object::Pad ':experimental(init_expr)';
83
84          use Object::Pad ':experimental(mop)';
85
86          use Object::Pad ':experimental(custom_field_attr)';
87
88          use Object::Pad ':experimental(adjust_params)';
89
90          use Object::Pad ':experimental';  # all of the above
91
92       Since version 0.64.
93
94       Multiple experimental features can be enabled at once by giving
95       multiple names in the parens, separated by spaces:
96
97          use Object::Pad ':experimental(init_expr mop)';
98
99   Automatic Construction
100       Classes are automatically provided with a constructor method, called
101       "new", which helps create the object instances. This may respond to
102       passed arguments, automatically assigning values of fields, and
103       invoking other blocks of code provided by the class. It proceeds in the
104       following stages:
105
106       The BUILDARGS phase
107
108       If the class provides a "BUILDARGS" class method, that is used to
109       mangle the list of arguments before the "BUILD" blocks are called. Note
110       this must be a class method not an instance method (and so implemented
111       using "sub"). It should perform any "SUPER" chaining as may be
112       required.
113
114          @args = $class->BUILDARGS( @_ )
115
116       Field assignment
117
118       If any field in the class has the ":param" attribute, then the
119       constructor will expect to receive its argmuents in an even-sized list
120       of name/value pairs. This applies even to fields inherited from the
121       parent class or applied roles. It is therefore a good idea to shape the
122       parameters to the constructor in this way in roles, and in classes if
123       you intend your class to be extended.
124
125       The constructor will also check for required parameters (these are all
126       the parameters for fields that do not have default initialisation
127       expressions). If any of these are missing an exception is thrown.
128
129       The BUILD phase
130
131       As part of the construction process, the "BUILD" block of every
132       component class will be invoked, passing in the list of arguments the
133       constructor was invoked with. Each class should perform its required
134       setup behaviour, but does not need to chain to the "SUPER" class first;
135       this is handled automatically.
136
137       The ADJUST phase
138
139       Next, the "ADJUST" block of every component class is invoked. This
140       happens after the fields are assigned their initial values and the
141       "BUILD" blocks have been run.
142
143       The strict-checking phase
144
145       Finally, before the object is returned, if the ":strict(params)" class
146       attribute is present, then the constructor will throw an exception if
147       there are any remaining named arguments left over after assigning them
148       to fields as per ":param" declarations, and running any "ADJUST"
149       blocks.
150

KEYWORDS

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

CREPT FEATURES

957       While not strictly part of being an object system, this module has
958       nevertheless gained a number of behaviours by feature creep, as they
959       have been found useful.
960
961   Implied Pragmata
962       In order to encourage users to write clean, modern code, the body of
963       the "class" block acts as if the following pragmata are in effect:
964
965          use strict;
966          use warnings;
967          no indirect ':fatal';  # or  no feature 'indirect' on perl 5.32 onwards
968          use feature 'signatures';
969
970       This list may be extended in subsequent versions to add further
971       restrictions and should not be considered exhaustive.
972
973       Further additions will only be ones that remove "discouraged" or
974       deprecated language features with the overall goal of enforcing a more
975       clean modern style within the body. As long as you write code that is
976       in a clean, modern style (and I fully accept that this wording is vague
977       and subjective) you should not find any new restrictions to be majorly
978       problematic. Either the code will continue to run unaffected, or you
979       may have to make some small alterations to bring it into a conforming
980       style.
981
982   Yield True
983       A "class" statement or block will yield a true boolean value. This
984       means that it can be used directly inside a .pm file, avoiding the need
985       to explicitly yield a true value from the end of it.
986

SUBCLASSING CLASSIC PERL CLASSES

988       There are a number of details specific to the case of deriving an
989       "Object::Pad" class from an existing classic Perl class that is not
990       implemented using "Object::Pad".
991
992   Storage of Instance Data
993       Instances will pick either the ":repr(HASH)" or ":repr(magic)" storage
994       type.
995
996   Object State During Methods Invoked By Superclass Constructor
997       It is common in classic Perl OO style to invoke methods on $self during
998       the constructor. This is supported here since "Object::Pad" version
999       0.19.  Note however that any methods invoked by the superclass
1000       constructor may not see the object in a fully consistent state. (This
1001       fact is not specific to using "Object::Pad" and would happen in classic
1002       Perl OO as well). The field initialisers will have been invoked but the
1003       "BUILD" and "ADJUST" blocks will not.
1004
1005       For example; in the following
1006
1007          package ClassicPerlBaseClass {
1008             sub new {
1009                my $self = bless {}, shift;
1010                say "Value seen by superconstructor is ", $self->get_value;
1011                return $self;
1012             }
1013             sub get_value { return "A" }
1014          }
1015
1016          class DerivedClass :isa(ClassicPerlBaseClass) {
1017             has $_value = "B";
1018             ADJUST {
1019                $_value = "C";
1020             }
1021             method get_value { return $_value }
1022          }
1023
1024          my $obj = DerivedClass->new;
1025          say "Value seen by user is ", $obj->get_value;
1026
1027       Until the "ClassicPerlBaseClass::new" superconstructor has returned the
1028       "ADJUST" block will not have been invoked. The $_value field will still
1029       exist, but its value will be "B" during the superconstructor. After the
1030       superconstructor, the "BUILD" and "ADJUST" blocks are invoked before
1031       the completed object is returned to the user. The result will therefore
1032       be:
1033
1034          Value seen by superconstructor is B
1035          Value seen by user is C
1036

STYLE SUGGESTIONS

1038       While in no way required, the following suggestions of code style
1039       should be noted in order to establish a set of best practices, and
1040       encourage consistency of code which uses this module.
1041
1042   $VERSION declaration
1043       While it would be nice for CPAN and other toolchain modules to parse
1044       the embedded version declarations in "class" statements, the current
1045       state at time of writing (June 2020) is that none of them actually do.
1046       As such, it will still be necessary to make a once-per-file $VERSION
1047       declaration in syntax those modules can parse.
1048
1049       Further note that these modules will also not parse the "class"
1050       declaration, so you will have to duplicate this with a "package"
1051       declaration as well as a "class" keyword. This does involve repeating
1052       the package name, so is slightly undesirable.
1053
1054       It is hoped that eventually upstream toolchain modules will be adapted
1055       to accept the "class" syntax as being sufficient to declare a package
1056       and set its version.
1057
1058       See also
1059
1060       • <https://github.com/Perl-Toolchain-Gang/Module-Metadata/issues/33>
1061
1062   File Layout
1063       Begin the file with a "use Object::Pad" line; ideally including a
1064       minimum-required version. This should be followed by the toplevel
1065       "package" and "class" declarations for the file. As it is at toplevel
1066       there is no need to use the block notation; it can be a unit class.
1067
1068       There is no need to "use strict" or apply other usual pragmata; these
1069       will be implied by the "class" keyword.
1070
1071          use Object::Pad 0.16;
1072
1073          package My::Classname 1.23;
1074          class My::Classname;
1075
1076          # other use statements
1077
1078          # has, methods, etc.. can go here
1079
1080   Field Names
1081       Field names should follow similar rules to regular lexical variables in
1082       code - lowercase, name components separated by underscores. For tiny
1083       examples such as "dumb record" structures this may be sufficient.
1084
1085          class Tag {
1086             field $name  :mutator;
1087             field $value :mutator;
1088          }
1089
1090       In larger examples with lots of non-trivial method bodies, it can get
1091       confusing to remember where the field variables come from (because we
1092       no longer have the "$self->{ ... }" visual clue). In these cases it is
1093       suggested to prefix the field names with a leading underscore, to make
1094       them more visually distinct.
1095
1096          class Spudger {
1097             field $_grapefruit;
1098
1099             ...
1100
1101             method mangle {
1102                $_grapefruit->peel; # The leading underscore reminds us this is a field
1103             }
1104          }
1105

WITH OTHER MODULES

1107   Syntax::Keyword::Dynamically
1108       A cross-module integration test asserts that "dynamically" works
1109       correctly on object instance fields:
1110
1111          use Object::Pad;
1112          use Syntax::Keyword::Dynamically;
1113
1114          class Container {
1115             has $value = 1;
1116
1117             method example {
1118                dynamically $value = 2;
1119                ,..
1120                # value is restored to 1 on return from this method
1121             }
1122          }
1123
1124   Future::AsyncAwait
1125       As of Future::AsyncAwait version 0.38 and Object::Pad version 0.15,
1126       both modules now use XS::Parse::Sublike to parse blocks of code.
1127       Because of this the two modules can operate together and allow class
1128       methods to be written as async subs which await expressions:
1129
1130          use Future::AsyncAwait;
1131          use Object::Pad;
1132
1133          class Example
1134          {
1135             async method perform ($block)
1136             {
1137                say "$self is performing code";
1138                await $block->();
1139                say "code finished";
1140             }
1141          }
1142
1143       These three modules combine; there is additionally a cross-module test
1144       to ensure that object instance fields can be "dynamically" set during a
1145       suspended "async method".
1146
1147   Devel::MAT
1148       When using Devel::MAT to help analyse or debug memory issues with
1149       programs that use "Object::Pad", you will likely want to additionally
1150       install the module Devel::MAT::Tool::Object::Pad. This will provide new
1151       commands and extend existing ones to better assist with analysing
1152       details related to "Object::Pad" classes and instances of them.
1153
1154          pmat> fields 0x55d7c173d4b8
1155          The field AV ARRAY(3)=NativeClass at 0x55d7c173d4b8
1156          Ix Field   Value
1157          0  $sfield SCALAR(UV) at 0x55d7c173d938 = 123
1158          ...
1159
1160          pmat> identify 0x55d7c17606d8
1161          REF() at 0x55d7c17606d8 is:
1162          XXthe %hfield field of ARRAY(3)=NativeClass at 0x55d7c173d4b8, which is:
1163          ...
1164

DESIGN TODOs

1166       The following points are details about the design of pad field-based
1167       object systems in general:
1168
1169       •   Is multiple inheritance actually required, if role composition is
1170           implemented including giving roles the ability to use private
1171           fields?
1172
1173       •   Consider the visibility of superclass fields to subclasses. Do
1174           subclasses even need to be able to see their superclass's fields,
1175           or are accessor methods always appropriate?
1176
1177           Concrete example: The "$self->{split_at}" access that
1178           Tickit::Widget::HSplit makes of its parent class
1179           Tickit::Widget::LinearSplit.
1180

IMPLEMENTATION TODOs

1182       These points are more about this particular module's implementation:
1183
1184       •   Consider multiple inheritance of subclassing, if that is still
1185           considered useful after adding roles.
1186
1187       •   Work out why "no indirect" doesn't appear to work properly before
1188           perl 5.20.
1189
1190       •   Work out why we don't get a "Subroutine new redefined at ..."
1191           warning if we
1192
1193             sub new { ... }
1194
1195       •   The "local" modifier does not work on field variables, because they
1196           appear to be regular lexicals to the parser at that point. A
1197           workaround is to use Syntax::Keyword::Dynamically instead:
1198
1199              use Syntax::Keyword::Dynamically;
1200
1201              field $loglevel;
1202
1203              method quietly {
1204                 dynamically $loglevel = LOG_ERROR;
1205                 ...
1206              }
1207

FEEDBACK

1209       The following resources are useful forms of providing feedback,
1210       especially in the form of reports of what you find good or bad about
1211       the module, requests for new features, questions on best practice,
1212       etc...
1213
1214       •   The RT queue at
1215           <https://rt.cpan.org/Dist/Display.html?Name=Object-Pad>.
1216
1217       •   The "#cor" IRC channel on "irc.perl.org".
1218

SPONSORS

1220       With thanks to the following sponsors, who have helped me be able to
1221       spend time working on this module and other perl features.
1222
1223       •   Oetiker+Partner AG <https://www.oetiker.ch/en/>
1224
1225       •   Deriv <http://deriv.com>
1226
1227       •   Perl-Verein Schweiz <https://www.perl-workshop.ch/>
1228
1229       Additional details may be found at
1230       <https://github.com/Ovid/Cor/wiki/Sponsors>.
1231

AUTHOR

1233       Paul Evans <leonerd@leonerd.org.uk>
1234
1235
1236
1237perl v5.36.0                      2022-12-01                    Object::Pad(3)
Impressum