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