1Object::Pad(3pm) User Contributed Perl Documentation Object::Pad(3pm)
2
3
4
6 "Object::Pad" - a simple syntax for lexical field-based objects
7
9 On perl version 5.26 onwards:
10
11 use v5.26;
12 use Object::Pad;
13
14 class Point {
15 field $x :param = 0;
16 field $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 field $x :param = 0;
36 field $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
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(mop)';
83
84 use Object::Pad ':experimental(custom_field_attr)';
85
86 use Object::Pad ':experimental(adjust_params)';
87
88 use Object::Pad ':experimental'; # all of the above
89
90 Since version 0.64.
91
92 Multiple experimental features can be enabled at once by giving
93 multiple names in the parens, separated by spaces:
94
95 use Object::Pad ':experimental(mop adjust_params)';
96
97 Automatic Construction
98 Classes are automatically provided with a constructor method, called
99 "new", which helps create the object instances. This may respond to
100 passed arguments, automatically assigning values of fields, and
101 invoking other blocks of code provided by the class. It proceeds in the
102 following stages:
103
104 The BUILDARGS phase
105
106 If the class provides a "BUILDARGS" class method, that is used to
107 mangle the list of arguments before the "BUILD" blocks are called. Note
108 this must be a class method not an instance method (and so implemented
109 using "sub"). It should perform any "SUPER" chaining as may be
110 required.
111
112 @args = $class->BUILDARGS( @_ )
113
114 Field assignment
115
116 If any field in the class has the ":param" attribute, then the
117 constructor will expect to receive its argmuents in an even-sized list
118 of name/value pairs. This applies even to fields inherited from the
119 parent class or applied roles. It is therefore a good idea to shape the
120 parameters to the constructor in this way in roles, and in classes if
121 you intend your class to be extended.
122
123 The constructor will also check for required parameters (these are all
124 the parameters for fields that do not have default initialisation
125 expressions). If any of these are missing an exception is thrown.
126
127 The BUILD phase
128
129 As part of the construction process, the "BUILD" block of every
130 component class will be invoked, passing in the list of arguments the
131 constructor was invoked with. Each class should perform its required
132 setup behaviour, but does not need to chain to the "SUPER" class first;
133 this is handled automatically.
134
135 The ADJUST phase
136
137 Next, the "ADJUST" block of every component class is invoked. This
138 happens after the fields are assigned their initial values and the
139 "BUILD" blocks have been run.
140
141 The strict-checking phase
142
143 Finally, before the object is returned, if the ":strict(params)" class
144 attribute is present, then the constructor will throw an exception if
145 there are any remaining named arguments left over after assigning them
146 to fields as per ":param" declarations, and running any "ADJUST"
147 blocks.
148
150 class
151 class Name :ATTRS... {
152 ...
153 }
154
155 class Name :ATTRS...;
156
157 Behaves similarly to the "package" keyword, but provides a package that
158 defines a new class. Such a class provides an automatic constructor
159 method called "new".
160
161 As with "package", an optional block may be provided. If so, the
162 contents of that block define the new class and the preceding package
163 continues afterwards. If not, it sets the class as the package context
164 of following keywords and definitions.
165
166 As with "package", an optional version declaration may be given. If so,
167 this sets the value of the package's $VERSION variable.
168
169 class Name VERSION { ... }
170
171 class Name VERSION;
172
173 A single superclass is supported by the keyword "isa"
174
175 Since version 0.41.
176
177 class Name isa BASECLASS {
178 ...
179 }
180
181 class Name isa BASECLASS BASEVER {
182 ...
183 }
184
185 Prior to version 0.41 this was called "extends", but since version 0.73
186 this is no longer recognised. The "isa" keyword is now deprecated, in
187 favour of the ":isa" attribute which is preferred because it follows a
188 more standard grammar without this special-case.
189
190 One or more roles can be composed into the class by the keyword "does"
191
192 Since version 0.41.
193
194 class Name does ROLE, ROLE,... {
195 ...
196 }
197
198 Prior to version 0.41 this was called "implements", but since version
199 0.73 this is no longer recognised. The "does" keyword is now
200 deprecated, in favour of the ":does" attribute which is preferred
201 because it follows a more standard grammar without this special-case.
202
203 An optional list of attributes may be supplied in similar syntax as for
204 subs or lexical variables. (These are annotations about the class
205 itself; the concept should not be confused with per-object-instance
206 data, which here is called "fields").
207
208 Whitespace is permitted within the value and is automatically trimmed,
209 but as standard Perl parsing rules, no space is permitted between the
210 attribute's name and the open parenthesis of its value:
211
212 :attr( value here ) # is permitted
213 :attr (value here) # not permitted
214
215 The following class attributes are supported:
216
217 :isa
218
219 :isa(CLASS)
220
221 :isa(CLASS CLASSVER)
222
223 Since version 0.57.
224
225 Declares a superclass that this class extends. At most one superclass
226 is supported.
227
228 If the package providing the superclass does not exist, an attempt is
229 made to load it by code equivalent to
230
231 require CLASS;
232
233 and thus it must either already exist, or be locatable via the usual
234 @INC mechanisms.
235
236 The superclass may or may not itself be implemented by "Object::Pad",
237 but if it is not then see "SUBCLASSING CLASSIC PERL CLASSES" for
238 further detail on the semantics of how this operates.
239
240 An optional version check can also be supplied; it performs the
241 equivalent of
242
243 BaseClass->VERSION( $ver )
244
245 :does
246
247 :does(ROLE)
248
249 :does(ROLE ROLEVER)
250
251 Since version 0.57.
252
253 Composes a role into the class; optionally requiring a version check on
254 the role package. This is a newer form of the "implements" and "does"
255 keywords and should be preferred for new code.
256
257 Multiple roles can be composed by using multiple ":does" attributes,
258 one per role.
259
260 The package will be loaded in a similar way to how the ":isa" attribute
261 is handled.
262
263 :repr(TYPE)
264
265 Sets the representation type for instances of this class. Must be one
266 of the following values:
267
268 :repr(native)
269
270 The native representation. This is an opaque representation type whose
271 contents are not specified. It only works for classes whose entire
272 inheritance hierarchy is built only from classes based on
273 "Object::Pad".
274
275 :repr(HASH)
276
277 The representation will be a blessed hash reference. The instance data
278 will be stored in an array referenced by a key called
279 "Object::Pad/slots", which is fairly unlikely to clash with existing
280 storage on the instance. No other keys will be used; they are available
281 for implementions and subclasses to use. The exact format of the value
282 stored here is not specified and may change between module versions,
283 though it can be relied on to be well-behaved as some kind of perl data
284 structure for purposes of modules like Data::Dumper or serialisation
285 into things like "YAML" or "JSON".
286
287 This representation type may be useful when converting existing classes
288 into using "Object::Pad" where there may be existing subclasses of it
289 that presume a blessed hash for their own use.
290
291 :repr(magic)
292
293 The representation will use MAGIC to apply the instance data in a way
294 that is invisible at the Perl level, and shouldn't get in the way of
295 other things the instance is doing even in XS modules.
296
297 This representation type is the only one that will work for subclassing
298 existing classes that do not use blessed hashes.
299
300 :repr(autoselect), :repr(default)
301
302 Since version 0.23.
303
304 This representation will select one of the representations above
305 depending on what is best for the situation. Classes not derived from a
306 non-"Object::Pad" base class will pick "native", and classes derived
307 from non-"Object::Pad" bases will pick either the "HASH" or "magic"
308 forms depending on whether the instance is a blessed hash reference or
309 some other kind.
310
311 This achieves the best combination of DWIM while still allowing the
312 common forms of hash reference to be inspected by "Data::Dumper", etc.
313 This is the default representation type, and does not have to be
314 specifically requested.
315
316 :strict(params)
317
318 Since version 0.43.
319
320 Can only be applied to classes that contain no "BUILD" blocks. If set,
321 then the constructor will complain about any unrecognised named
322 arguments passed to it (i.e. names that do not correspond to the
323 ":param" of any defined field and left unconsumed by any "ADJUST"
324 block).
325
326 Since "BUILD" blocks can inspect the arguments arbitrarily, the
327 presence of any such block means the constructor cannot determine which
328 named arguments are not recognised.
329
330 This attribute is a temporary stepping-stone for compatibility with
331 existing code. It is recommended to enable this whenever possible, as a
332 later version of this module will likely perform this behaviour
333 unconditionally whenever no "BUILD" blocks are present.
334
335 role
336 role Name :ATTRS... {
337 ...
338 }
339
340 role Name :ATTRS...;
341
342 Since version 0.32.
343
344 Similar to "class", but provides a package that defines a new role. A
345 role acts similar to a class in some respects, and differently in
346 others.
347
348 Like a class, a role can have a version, and named methods.
349
350 role Name VERSION {
351 method a { ... }
352 method b { ... }
353 }
354
355 A role does not provide a constructor, and instances cannot directly be
356 constructed. A role cannot extend a class.
357
358 A role can declare that it requires methods of given names from any
359 class that implements the role.
360
361 role Name {
362 requires METHOD;
363 }
364
365 A role can provide instance fields. These are visible to any "ADJUST"
366 blocks or methods provided by that role.
367
368 Since version 0.33.
369
370 role Name {
371 field $f;
372
373 ADJUST { $f = "a value"; }
374
375 method f { return $f; }
376 }
377
378 Since version 0.57 a role can declare that it provides another role:
379
380 role Name :does(OTHERROLE) { ... }
381 role Name :does(OTHERROLE OTHERVER) { ... }
382
383 This will include all of the methods from the included role.
384 Effectively this means that applying the "outer" role to a class will
385 imply applying the other role as well.
386
387 The following role attributes are supported:
388
389 :compat(invokable)
390
391 Since version 0.35.
392
393 Enables a form of backward-compatibility behaviour useful for gradually
394 upgrading existing code from classical Perl inheritance or mixins into
395 using roles.
396
397 Normally, methods of a role cannot be directly invoked and the role
398 must be applied to an Object::Pad-based class in order to be used. This
399 however presents a problem when gradually upgrading existing code that
400 already uses techniques like roles, multiple inheritance or mixins when
401 that code may be split across multiple distributions, or for some other
402 reason cannot be upgraded all at once. Methods within a role that has
403 the :compat(invokable) attribute applied to it may be directly invoked
404 on any object instance. This allows the creation of a role that can
405 still provide code for existing classes written in classical Perl that
406 has not yet been rewritten to use "Object::Pad".
407
408 The tradeoff is that a :compat(invokable) role may not create field
409 data using the "field" keyword. Whatever behaviours the role wishes to
410 perform must be provided only by calling other methods on $self, or
411 perhaps by making assumptions about the representation type of
412 instances.
413
414 It should be stressed again: This option is only intended for gradual
415 upgrade of existing classical Perl code into using "Object::Pad". When
416 all existing code is using "Object::Pad" then this attribute can be
417 removed from the role.
418
419 field
420 field $var;
421 field @var;
422 field %var;
423
424 field $var :ATTR ATTR...;
425
426 field $var = EXPR;
427
428 field $var //= EXPR;
429 field $var ||= EXPR;
430
431 field $var { BLOCK }
432
433 Since version 0.66.
434
435 Declares that the instances of the class or role have a member field of
436 the given name. This member field will be accessible as a lexical
437 variable within any "method" declarations in the class.
438
439 Array and hash members are permitted and behave as expected; you do not
440 need to store references to anonymous arrays or hashes.
441
442 Member fields are private to a class or role. They are not visible to
443 users of the class, nor inherited by subclasses nor any class that a
444 role is applied to. In order to provide access to them a class may wish
445 to use "method" to create an accessor, or use the attributes such as
446 ":reader" to get one generated.
447
448 The following field attributes are supported:
449
450 :reader, :reader(NAME)
451
452 Since version 0.27.
453
454 Generates a reader method to return the current value of the field. If
455 no name is given, the name of the field is used. A single prefix
456 character "_" will be removed if present.
457
458 field $x :reader;
459
460 # equivalent to
461 field $x; method x { return $x }
462
463 Since version 0.55 these are permitted on any field type, but prior
464 versions only allowed them on scalar fields. The reader method behaves
465 identically to how a lexical variable would behave in the same context;
466 namely returning a list of values from an array or key/value pairs from
467 a hash when in list context, or the number of items or keys when in
468 scalar context.
469
470 field @items :reader;
471
472 foreach my $item ( $obj->items ) { ... } # iterates the list of items
473
474 my $count = $obj->items; # yields count of items
475
476 :writer, :writer(NAME)
477
478 Since version 0.27.
479
480 Generates a writer method to set a new value of the field from its
481 arguments. If no name is given, the name of the field is used prefixed
482 by "set_". A single prefix character "_" will be removed if present.
483
484 field $x :writer;
485
486 # equivalent to
487 field $x; method set_x { $x = shift; return $self }
488
489 Since version 0.28 a generated writer method will return the object
490 invocant itself, allowing a chaining style.
491
492 $obj->set_x("x")
493 ->set_y("y")
494 ->set_z("z");
495
496 Since version 0.55 these are permitted on any field type, but prior
497 versions only allowed them on scalar fields. On arrays or hashes, the
498 writer method takes a list of values to be assigned into the field,
499 completely replacing any values previously there.
500
501 :mutator, :mutator(NAME)
502
503 Since version 0.27.
504
505 Generates an lvalue mutator method to return or set the value of the
506 field. These are only permitted for scalar fields. If no name is
507 given, the name of the field is used. A single prefix character "_"
508 will be removed if present.
509
510 field $x :mutator;
511
512 # equivalent to
513 field $x; method x :lvalue { $x }
514
515 Since version 0.28 all of these generated accessor methods will include
516 argument checking similar to that used by subroutine signatures, to
517 ensure the correct number of arguments are passed - usually zero, but
518 exactly one in the case of a ":writer" method.
519
520 :accessor, :accessor(NAME)
521
522 Since version 0.53.
523
524 Generates a combined reader-writer accessor method to set or return the
525 value of the field. These are only permitted for scalar fields. If no
526 name is given, the name of the field is used. A prefix character "_"
527 will be removed if present.
528
529 This method takes either zero or one additional arguments. If an
530 argument is passed, the value of the field is set from this argument
531 (even if it is "undef"). If no argument is passed (i.e. "scalar @_" is
532 false) then the field is not modified. In either case, the value of the
533 field is then returned.
534
535 field $x :accessor;
536
537 # equivalent to
538 field $x;
539
540 method x {
541 $x = shift if @_;
542 return $x;
543 }
544
545 :weak
546
547 Since version 0.44.
548
549 Generated code which sets the value of this field will weaken it if it
550 contains a reference. This applies to within the constructor if
551 ":param" is given, and to a ":writer" accessor method. Note that this
552 only applies to automatically generated code; not normal code written
553 in regular method bodies. If you assign into the field variable you
554 must remember to call "Scalar::Util::weaken" (or "builtin::weaken" on
555 Perl 5.36 or above) yourself.
556
557 :param, :param(NAME)
558
559 Since version 0.41.
560
561 Sets this field to be initialised automatically in the generated
562 constructor. This is only permitted on scalar fields. If no name is
563 given, the name of the field is used. A single prefix character "_"
564 will be removed if present.
565
566 Any field that has ":param" but does not have a default initialisation
567 expression or block becomes a required argument to the constructor.
568 Attempting to invoke the constructor without a named argument for this
569 will throw an exception. In order to make a parameter optional, make
570 sure to give it a default expression - even if that expression is
571 "undef":
572
573 field $x :param; # this is required
574 field $z :param = undef; # this is optional
575
576 Any field that has a ":param" and an initialisation block will only run
577 the code in the block if required by the constructor. If a named
578 parameter is passed to the constructor for this field, then its code
579 block will not be executed.
580
581 Values for fields are assigned by the constructor before any "BUILD"
582 blocks are invoked.
583
584 Field Initialiser Expressions
585
586 Since version 0.54 a deferred statement block is also permitted, on any
587 field variable type. This permits code to be executed as part of the
588 instance constructor, rather than running just once when the class is
589 set up. Code in a field initialisation block is roughly equivalent to
590 being placed in a "BUILD" or "ADJUST" block.
591
592 Since version 0.73 this may also be written as a plain expression
593 introduced by an equals symbol ("="). This is equivalent to using a
594 block. Note carefully: the equals symbol is part of the "field"
595 syntax; it is not simply a runtime assignment operator that happens
596 once at the time the class is declared. Just like the block form
597 describe above, the expression is evaluated during the constructor of
598 every instance.
599
600 Since version 0.74 this expression may also be written using a defined-
601 or or logical-or assignment operator ("//=" or "||="). In these case,
602 the default expression will be evaluated and assigned if the caller did
603 not pass a value to the constructor at all, or if the value passed was
604 undef (for "//=") or false (for "||="). For most scalar parameters,
605 where "undef" is not a valid value, you probably wanted to use "//=" to
606 assign defaults.
607
608 class Action {
609 field $timeout :param //= 20;
610 ...
611 }
612
613 # The default of 20 will apply here too
614 my $act = Action->new( timeout => $opts{timeout} );
615
616 Note that $self is specifically not visible during an initialiser
617 expression. This is because the object is not yet fully constructed, so
618 it would be dangerous to allow access to it while in this state.
619 However, the "__CLASS__" keyword is available, so initialiser
620 expressions can make use of class-based dispatch to invoke class-level
621 methods to help provide values.
622
623 Field initialier expressions were originally experimental, but since
624 version 0.800 no longer emit experimental warnings.
625
626 Since version 0.76 expressions that are purely compiletime constants
627 (either as single scalars or entire lists of constants) are no longer
628 considered experimental. They can be used without silencing the
629 warning.
630
631 Control flow that attempts to leave a field initialiser expression or
632 block is not permitted. This includes any "return" expression, any
633 "next/last/redo" outside of a loop, with a dynamically-calculated label
634 expression, or with a label that it doesn't appear in. "goto"
635 statements are also currently forbidden, though known-safe ones may be
636 permitted in future.
637
638 Loop control expressions that are known at compiletime to affect a loop
639 that they appear within are permitted.
640
641 field $x { foreach(@list) { next; } } # this is fine
642
643 field $x { LOOP: while(1) { last LOOP; } } # this is fine too
644
645 has
646 has $var;
647 has @var;
648 has %var;
649
650 has $var = EXPR;
651
652 has $var { BLOCK }
653
654 A now-deprecated older version of the "field" keyword.
655
656 This generally behaves like "field", except that inline expressions are
657 evaluated immediately, once, during class declaration time. These are
658 not stored to be evaluated for each constructor.
659
660 Because of the one-shot immediate nature of these initialisation
661 expressions (and a bunch of other reasons), the "has" keyword is now
662 discouraged for use and will emit compile-time warnings in the
663 "deprecated" category. Use the "field" keyword instead.
664
665 If you need to evaluate an expression exactly once during the class
666 declaration and assign its now-constant value to every instace, store
667 it in a regular "my" variable instead:
668
669 my $default_var = EXPR;
670 field $var = $default_var;
671
672 method
673 method NAME {
674 ...
675 }
676
677 method NAME (SIGNATURE) {
678 ...
679 }
680
681 method NAME :ATTRS... {
682 ...
683 }
684
685 method NAME;
686
687 Declares a new named method. This behaves similarly to the "sub"
688 keyword, except that within the body of the method all of the member
689 fields are also accessible. In addition, the method body will have a
690 lexical called $self which contains the invocant object directly; it
691 will already have been shifted from the @_ array.
692
693 If the method has no body and is given simply as a name, this declares
694 a required method for a role. Such a method must be provided by any
695 class that implements the role. It will be a compiletime error to
696 combine the role with a class that does not provide this.
697
698 The "signatures" feature is automatically enabled for method
699 declarations. In this case the signature does not have to account for
700 the invocant instance; that is handled directly.
701
702 method m ($one, $two) {
703 say "$self invokes method on one=$one two=$two";
704 }
705
706 ...
707 $obj->m(1, 2);
708
709 A list of attributes may be supplied as for "sub". The most useful of
710 these is ":lvalue", allowing easy creation of read-write accessors for
711 fields (but see also the ":reader", ":writer" and ":mutator" field
712 attributes).
713
714 class Counter {
715 field $count;
716
717 method count :lvalue { $count }
718 }
719
720 my $c = Counter->new;
721 $c->count++;
722
723 Every method automatically gets the ":method" attribute applied, which
724 suppresses warnings about ambiguous calls resolved to core functions if
725 the name of a method matches a core function.
726
727 The following additional attributes are recognised by "Object::Pad"
728 directly:
729
730 :override
731
732 Since version 0.29.
733
734 Marks that this method expects to override another of the same name
735 from a superclass. It is an error at compiletime if the superclass does
736 not provide such a method.
737
738 :common
739
740 Since version 0.62.
741
742 Marks that this method is a class-common method, instead of a regular
743 instance method. A class-common method may be invoked on class names
744 instead of instances. Within the method body there is a lexical $class
745 available, rather than $self. Because it is not associated with a
746 particular object instance, a class-common method cannot see instance
747 fields.
748
749 method (lexical)
750 method $var { ... }
751
752 method $var :ATTRS... (SIGNATURE) { ... }
753
754 Since version 0.59.
755
756 Declares a new lexical method. Lexical methods are not visible via the
757 package namespace, but instead are stored directly in a lexical
758 variable (with the same scoping rules as regular "my" variables). These
759 can be invoked by subsequent method code in the same block by using
760 "$self->$var(...)" method call syntax.
761
762 class WithPrivate {
763 field $var;
764
765 # Lexical methods can still see instance fields as normal
766 method $inc_var { $var++; say "Var was incremented"; }
767 method $dec_var { $var--; say "Var was decremented"; }
768
769 method bump {
770 $self->$inc_var;
771 say "In the middle";
772 $self->$dec_var;
773 }
774 }
775
776 my $obj = WithPrivate->new;
777
778 $obj->bump;
779
780 # Neither $inc_var nor $dec_var are visible here
781
782 This effectively provides the ability to define private methods, as
783 they are inaccessible from outside the block that defines the class. In
784 addition, there is no chance of a name collision because lexical
785 variables in different scopes are independent, even if they share the
786 same name. This is particularly useful in roles, to create internal
787 helper methods without letting those methods be visible to callers, or
788 risking their names colliding with other named methods defined on the
789 consuming class.
790
791 BUILD
792 BUILD {
793 ...
794 }
795
796 BUILD (SIGNATURE) {
797 ...
798 }
799
800 Since version 0.27.
801
802 Declares the builder block for this component class. A builder block
803 may use subroutine signature syntax, as for methods, to assist in
804 unpacking its arguments. A build block is not a subroutine and thus is
805 not permitted to use subroutine attributes (for example ":lvalue").
806
807 Note that a "BUILD" block is a named phaser block and not a method.
808 Attempts to create a method named "BUILD" (i.e. with syntax "method
809 BUILD {...}") will fail with a compiletime error, to avoid this
810 confusion.
811
812 ADJUST
813 ADJUST {
814 ...
815 }
816
817 Since version 0.43.
818
819 Declares an adjust block for this component class. This block of code
820 runs within the constructor, after any "BUILD" blocks and automatic
821 field value assignment. It can make any final adjustments to the
822 instance (such as initialising fields from calculated values).
823
824 An adjust block is not a subroutine and thus is not permitted to use
825 subroutine attributes (except see below). Note that an "ADJUST" block
826 is a named phaser block and not a method; it does not use the "sub" or
827 "method" keyword.
828
829 Currently, an "ADJUST" block receives a reference to the hash
830 containing the current constructor arguments, as per "ADJUSTPARAMS"
831 (see below). This was added in version 0.66 but will be removed again
832 as it conflicts with the more flexible and generally nicer named-
833 parameter "ADJUST :params" syntax (see below). Such uses should be
834 considered deprecated. A warning will be printed to indicate this
835 whenever an "ADJUST" block uses a signature. This warning can be
836 quieted by using "ADJUSTPARAMS" instead. Additionally, a warning may be
837 printed on code that attempts to access the params hashref via the @_
838 array.
839
840 ADJUST :params
841 ADJUST :params ( :$var1, :$var2, ... ) {
842 ...
843 }
844
845 ADJUST :params ( :$var1, :$var2, ..., %varN ) {
846 ...
847 }
848
849 Since version 0.70.
850
851 An "ADJUST" block can marked with a ":params" attribute, meaning that
852 it consumes additional constructor parameters by assigning them into
853 lexical variables.
854
855 This feature should be considered experimental, and will emit warnings
856 to that effect. They can be silenced with
857
858 use Object::Pad ':experimental(adjust_params)';
859
860 Before the block itself, a list of lexical variables are introduced,
861 inside parentheses. The name of each one is preceeded by a colon, and
862 consumes a constructor parameter of the same name. These parameters are
863 considered "consumed" for the purposes of a :strict(params) check.
864
865 A named parameter may be provided with default expression, which is
866 evaluated if no matching named argument is provided to the constructor.
867 As with fields, if a named parameter has no defaulting expression it
868 becomes a required argument to the constructor; an exception is thrown
869 by the constructor if it absent.
870
871 For example,
872
873 ADJUST :params ( :$x, :$y = "default", :$z ) { ... }
874
875 Note here that "x" and "z" are required parameters for the constructor
876 of a class containing this block, but "y" is an optional parameter
877 whose value will be filled in by the expression if not provided.
878 Because these parameters are named and not positional, there is no
879 ordering constraint; required and optional parameters can be freely
880 mixed.
881
882 Optional parameters can also use the "//=" and "||=" operators to
883 provide a default expression. In these cases, the default will be
884 applied if the caller did not provide the named argument at all, or if
885 the provided value was not defined (for "//=") or not true (for "||=").
886
887 ADJUST :params ( :$name //= "unnamed" ) { ... }
888
889 Like with subroutine signature parameters, every declared named
890 parameter is visible to the defaulting expression of all the later
891 ones. This permits values to be calculated based on other ones. For
892 example,
893
894 ADJUST :params ( :$thing = undef, :$things = [ $thing ] ) {
895 # Here, @$things is a list of values
896 }
897
898 This permits the caller to pass a list of values via an array reference
899 in the "things" parameter, or a single value in "thing".
900
901 The final element may be a regular hash variable. This requests that
902 all remaining named parameters are made available inside it. The code
903 in the block should "delete" from this hash any parameters it wishes to
904 consume, as with the earlier case above.
905
906 It is unspecified whether named fields or parameters for subclasses yet
907 to be processed are visible to hashes of earlier superclasses. In the
908 current implementation they are, but code should not rely on this fact.
909
910 Note also that there must be a space between the ":params" attribute
911 and the parentheses holding the named parameters. If this space is not
912 present, perl will parse the parentheses as if they are the value to
913 the :params() attribute, and this will fail to parse as intended. As
914 with other attributes and subroutine signatures, this whitespace is
915 significant.
916
917 (This notation is borrowed from a plan to add named parameter support
918 to perl's subroutine signature syntax).
919
920 ADJUSTPARAMS
921 Since version 0.51.
922
923 ADJUSTPARAMS ( $params ) { # on perl 5.26 onwards
924 ...
925 }
926
927 ADJUST {
928 my $params = shift;
929 ...
930 }
931
932 A variant of an "ADJUST" block that receives a reference to the hash
933 containing the current constructor parameters. This hash will not
934 contain any constructor parameters already consumed by ":param"
935 declarations on any fields, but only the leftovers once those are
936 processed.
937
938 The code in the block should "delete" from this hash any parameters it
939 wishes to consume. Once all the "ADJUST" blocks have run, any remaining
940 keys in the hash will be considered errors, subject to the
941 ":strict(params)" check.
942
943 __CLASS__
944 my $classname = __CLASS__;
945
946 Since version 0.72.
947
948 Only valid within the body (or signature) of a "method", an "ADJUST"
949 block, or the initialising expression of a "field". Yields the class
950 name of the instance that the method, block or expression is invoked
951 on.
952
953 This is similar to the core perl "__PACKAGE__" constant, except that it
954 cares about the dynamic class of the actual instance, not the static
955 class the code belongs to. When invoked by a subclass instance that
956 inherited code from its superclass it yields the name of the class of
957 the instance regardless of which class defined the code.
958
959 For example,
960
961 class BaseClass {
962 ADJUST { say "Constructing an instance of " . __CLASS__; }
963 }
964
965 class DerivedClass :isa(BaseClass) { }
966
967 my $obj = DerivedClass->new;
968
969 Will produce the following output
970
971 Constructing an instance of DerivedClass
972
973 This is particularly useful in field initialisers for invoking
974 (constant) methods on the invoking class to provide default values for
975 fields. This way a subclass could provide a different value.
976
977 class Timer {
978 use constant DEFAULT_DURATION => 60;
979 field $duration = __CLASS__->DEFAULT_DURATION;
980 }
981
982 class ThreeMinuteTimer :isa(Timer) {
983 use constant DEFAULT_DURATION => 3 * 60;
984 }
985
986 requires
987 requires NAME;
988
989 Declares that this role requires a method of the given name from any
990 class that implements it. It is an error at compiletime if the
991 implementing class does not provide such a method.
992
993 This form of declaring a required method is now vaguely discouraged, in
994 favour of the bodyless "method" form described above.
995
997 While not strictly part of being an object system, this module has
998 nevertheless gained a number of behaviours by feature creep, as they
999 have been found useful.
1000
1001 Implied Pragmata
1002 The following behaviour is likely to be removed in a later version of
1003 this module.
1004
1005 In order to encourage users to write clean, modern code, the body of
1006 the "class" block currently acts as if the following pragmata are in
1007 effect:
1008
1009 use strict;
1010 use warnings;
1011 no indirect ':fatal'; # or no feature 'indirect' on perl 5.32 onwards
1012 use feature 'signatures';
1013
1014 This behaviour was designed early around the original "line-0" version
1015 of the Perl 7 plan, which has subsequently been found to be a bad
1016 design and abandoned. That leaves this module in an unfortunate
1017 situation, because its behaviour here does not match the plans for core
1018 perl; where the recently-added "class" keyword does none of this,
1019 although the "method" keyword always behaves as if signatures were
1020 enabled anyway.
1021
1022 It is eventually planned that this behaviour will be removed from
1023 "Object::Pad" entirely (except for enabling the "signatures" feature).
1024 While that won't in itself break any existing code, it would mean that
1025 code which previously ran with the protection of "strict" and
1026 "warnings" would now not be. A satisfactory solution to this problem
1027 has not yet been found, but until then it is suggested that code using
1028 this module remembers to explicitly enable this set of pragmata before
1029 using the "class" keyword.
1030
1031 A handy way to do this is to use the "use VERSION" syntax; v5.36 or
1032 later will already perform all of the pragmata listed above.
1033
1034 use v5.36;
1035
1036 If you import this module with a module version number of 0.800 or
1037 higher it will enable a warning if you forget to enable "strict" and
1038 "warnings" before using the "class" or "roll" keywords:
1039
1040 use Object::Pad 0.800;
1041
1042 class X { ... }
1043
1044 class keyword enabled 'use strict' but this will be removed in a later version at FILE line 3.
1045 class keyword enabled 'use warnings' but this will be removed in a later version at FILE line 3.
1046
1047 Yield True
1048 The following behaviour is likely to be removed in a later version of
1049 this module.
1050
1051 A "class" statement or block will yield a true boolean value. This
1052 means that it can be used directly inside a .pm file, avoiding the need
1053 to explicitly yield a true value from the end of it.
1054
1055 As with the implied pragmata above, this behaviour has also been found
1056 to be a bad design and will likely be removed soon. For now it is
1057 suggested not to rely on it and instead either use the new
1058 "module_true" feature already part of the "use v5.38" pragma, or on
1059 older perls simply remember to put an explicit true value at the end of
1060 the file.
1061
1063 There are a number of details specific to the case of deriving an
1064 "Object::Pad" class from an existing classic Perl class that is not
1065 implemented using "Object::Pad".
1066
1067 Storage of Instance Data
1068 Instances will pick either the :repr(HASH) or :repr(magic) storage
1069 type.
1070
1071 Object State During Methods Invoked By Superclass Constructor
1072 It is common in classic Perl OO style to invoke methods on $self during
1073 the constructor. This is supported here since "Object::Pad" version
1074 0.19. Note however that any methods invoked by the superclass
1075 constructor may not see the object in a fully consistent state. (This
1076 fact is not specific to using "Object::Pad" and would happen in classic
1077 Perl OO as well). The field initialisers will have been invoked but the
1078 "BUILD" and "ADJUST" blocks will not.
1079
1080 For example; in the following
1081
1082 package ClassicPerlBaseClass {
1083 sub new {
1084 my $self = bless {}, shift;
1085 say "Value seen by superconstructor is ", $self->get_value;
1086 return $self;
1087 }
1088 sub get_value { return "A" }
1089 }
1090
1091 class DerivedClass :isa(ClassicPerlBaseClass) {
1092 field $_value = "B";
1093 ADJUST {
1094 $_value = "C";
1095 }
1096 method get_value { return $_value }
1097 }
1098
1099 my $obj = DerivedClass->new;
1100 say "Value seen by user is ", $obj->get_value;
1101
1102 Until the "ClassicPerlBaseClass::new" superconstructor has returned the
1103 "ADJUST" block will not have been invoked. The $_value field will still
1104 exist, but its value will be "B" during the superconstructor. After the
1105 superconstructor, the "BUILD" and "ADJUST" blocks are invoked before
1106 the completed object is returned to the user. The result will therefore
1107 be:
1108
1109 Value seen by superconstructor is B
1110 Value seen by user is C
1111
1113 While in no way required, the following suggestions of code style
1114 should be noted in order to establish a set of best practices, and
1115 encourage consistency of code which uses this module.
1116
1117 $VERSION declaration
1118 While it would be nice for CPAN and other toolchain modules to parse
1119 the embedded version declarations in "class" statements, the current
1120 state at time of writing (June 2020) is that none of them actually do.
1121 As such, it will still be necessary to make a once-per-file $VERSION
1122 declaration in syntax those modules can parse.
1123
1124 Further note that these modules will also not parse the "class"
1125 declaration, so you will have to duplicate this with a "package"
1126 declaration as well as a "class" keyword. This does involve repeating
1127 the package name, so is slightly undesirable.
1128
1129 It is hoped that eventually upstream toolchain modules will be adapted
1130 to accept the "class" syntax as being sufficient to declare a package
1131 and set its version.
1132
1133 See also
1134
1135 • <https://github.com/Perl-Toolchain-Gang/Module-Metadata/issues/33>
1136
1137 File Layout
1138 Begin the file with a "use Object::Pad" line; ideally including a
1139 minimum-required version. This should be followed by the toplevel
1140 "package" and "class" declarations for the file. As it is at toplevel
1141 there is no need to use the block notation; it can be a unit class.
1142
1143 There is no need to "use strict" or apply other usual pragmata; these
1144 will be implied by the "class" keyword.
1145
1146 use Object::Pad 0.16;
1147
1148 package My::Classname 1.23;
1149 class My::Classname;
1150
1151 # other use statements
1152
1153 # field, methods, etc.. can go here
1154
1155 Field Names
1156 Field names should follow similar rules to regular lexical variables in
1157 code - lowercase, name components separated by underscores. For tiny
1158 examples such as "dumb record" structures this may be sufficient.
1159
1160 class Tag {
1161 field $name :mutator;
1162 field $value :mutator;
1163 }
1164
1165 In larger examples with lots of non-trivial method bodies, it can get
1166 confusing to remember where the field variables come from (because we
1167 no longer have the "$self->{ ... }" visual clue). In these cases it is
1168 suggested to prefix the field names with a leading underscore, to make
1169 them more visually distinct.
1170
1171 class Spudger {
1172 field $_grapefruit;
1173
1174 ...
1175
1176 method mangle {
1177 $_grapefruit->peel; # The leading underscore reminds us this is a field
1178 }
1179 }
1180
1182 Syntax::Keyword::Dynamically
1183 A cross-module integration test asserts that "dynamically" works
1184 correctly on object instance fields:
1185
1186 use Object::Pad;
1187 use Syntax::Keyword::Dynamically;
1188
1189 class Container {
1190 field $value = 1;
1191
1192 method example {
1193 dynamically $value = 2;
1194 ,..
1195 # value is restored to 1 on return from this method
1196 }
1197 }
1198
1199 Future::AsyncAwait
1200 As of Future::AsyncAwait version 0.38 and Object::Pad version 0.15,
1201 both modules now use XS::Parse::Sublike to parse blocks of code.
1202 Because of this the two modules can operate together and allow class
1203 methods to be written as async subs which await expressions:
1204
1205 use Future::AsyncAwait;
1206 use Object::Pad;
1207
1208 class Example
1209 {
1210 async method perform ($block)
1211 {
1212 say "$self is performing code";
1213 await $block->();
1214 say "code finished";
1215 }
1216 }
1217
1218 These three modules combine; there is additionally a cross-module test
1219 to ensure that object instance fields can be "dynamically" set during a
1220 suspended "async method".
1221
1222 Devel::MAT
1223 When using Devel::MAT to help analyse or debug memory issues with
1224 programs that use "Object::Pad", you will likely want to additionally
1225 install the module Devel::MAT::Tool::Object::Pad. This will provide new
1226 commands and extend existing ones to better assist with analysing
1227 details related to "Object::Pad" classes and instances of them.
1228
1229 pmat> fields 0x55d7c173d4b8
1230 The field AV ARRAY(3)=NativeClass at 0x55d7c173d4b8
1231 Ix Field Value
1232 0 $sfield SCALAR(UV) at 0x55d7c173d938 = 123
1233 ...
1234
1235 pmat> identify 0x55d7c17606d8
1236 REF() at 0x55d7c17606d8 is:
1237 └─the %hfield field of ARRAY(3)=NativeClass at 0x55d7c173d4b8, which is:
1238 ...
1239
1241 The following points are details about the design of pad field-based
1242 object systems in general:
1243
1244 • Is multiple inheritance actually required, if role composition is
1245 implemented including giving roles the ability to use private
1246 fields?
1247
1248 • Consider the visibility of superclass fields to subclasses. Do
1249 subclasses even need to be able to see their superclass's fields,
1250 or are accessor methods always appropriate?
1251
1252 Concrete example: The "$self->{split_at}" access that
1253 Tickit::Widget::HSplit makes of its parent class
1254 Tickit::Widget::LinearSplit.
1255
1257 These points are more about this particular module's implementation:
1258
1259 • Consider multiple inheritance of subclassing, if that is still
1260 considered useful after adding roles.
1261
1262 • Work out why "no indirect" doesn't appear to work properly before
1263 perl 5.20.
1264
1265 • Work out why we don't get a "Subroutine new redefined at ..."
1266 warning if we
1267
1268 sub new { ... }
1269
1270 • The "local" modifier does not work on field variables, because they
1271 appear to be regular lexicals to the parser at that point. A
1272 workaround is to use Syntax::Keyword::Dynamically instead:
1273
1274 use Syntax::Keyword::Dynamically;
1275
1276 field $loglevel;
1277
1278 method quietly {
1279 dynamically $loglevel = LOG_ERROR;
1280 ...
1281 }
1282
1284 The following resources are useful forms of providing feedback,
1285 especially in the form of reports of what you find good or bad about
1286 the module, requests for new features, questions on best practice,
1287 etc...
1288
1289 • The RT queue at
1290 <https://rt.cpan.org/Dist/Display.html?Name=Object-Pad>.
1291
1292 • The "#cor" IRC channel on "irc.perl.org".
1293
1295 With thanks to the following sponsors, who have helped me be able to
1296 spend time working on this module and other perl features.
1297
1298 • Oetiker+Partner AG <https://www.oetiker.ch/en/>
1299
1300 • Deriv <http://deriv.com>
1301
1302 • Perl-Verein Schweiz <https://www.perl-workshop.ch/>
1303
1304 Additional details may be found at
1305 <https://github.com/Ovid/Cor/wiki/Sponsors>.
1306
1308 Paul Evans <leonerd@leonerd.org.uk>
1309
1310
1311
1312perl v5.38.0 2023-08-10 Object::Pad(3pm)