Debian Codegraph @

README

raw
1 NAME
2
3 Object::Pad - a simple syntax for lexical field-based objects
4
5 SYNOPSIS
6
7 On perl version 5.26 onwards:
8
9 use v5.26;
10 use Object::Pad;
11
12 class Point {
13 field $x :param = 0;
14 field $y :param = 0;
15
16 method move ($dX, $dY) {
17 $x += $dX;
18 $y += $dY;
19 }
20
21 method describe () {
22 print "A point at ($x, $y)\n";
23 }
24 }
25
26 Point->new(x => 5, y => 10)->describe;
27
28 Or, for older perls that lack signatures:
29
30 use Object::Pad;
31
32 class Point {
33 field $x :param = 0;
34 field $y :param = 0;
35
36 method move {
37 my ($dX, $dY) = @_;
38 $x += $dX;
39 $y += $dY;
40 }
41
42 method describe {
43 print "A point at ($x, $y)\n";
44 }
45 }
46
47 Point->new(x => 5, y => 10)->describe;
48
49 DESCRIPTION
50
51 This module provides a simple syntax for creating object classes, which
52 uses private variables that look like lexicals as object member fields.
53
54 Relation to use feature 'class'
55
56 Since its original creation, this module has evolved to become the
57 test-bed for refining the design of what a good class-based object
58 system would look like for Perl. While useful in its own right, it also
59 acts as a preview of what Perl's use feature 'class' syntax will likely
60 become. Being a CPAN module, this can be iterated much faster than core
61 Perl, which only gets one major release per year. Getting the design
62 right in this module first therefore helps to reduce the amount of
63 development time needed in core Perl.
64
65 Where features overlap, both this module and the class feature added to
66 recent Perl versions should largely agree on syntax and semantics. This
67 module will likely always be ahead of core Perl in terms of exact
68 abilties because it is acting as a test-bed for these new ideas.
69 However, where both implementations support the same idea, they should
70 in general use the same syntax and semantics to provide it.
71
72 If you are interested in using this object system in new code in a way
73 that will be forward-compatible with the feature added directly in
74 newer Perl versions, while also supporting versions of Perl before this
75 feature was added, you may wish to use instead the module
76 Feature::Compat::Class. That module enables the core Perl feature on
77 the latest version of Perl, or uses Object::Pad to fill in the missing
78 syntax and features on older Perl versions.
79
80 Experimental Features
81
82 Since version 0.63.
83
84 While most of this module has evolved into a stable state,
85 recently-added parts remain experimental because the design is still
86 evolving, and many features and ideas have yet to implemented. Of these
87 experimental features, feel free to try them out in newly-developed
88 code, but don't complain if a later version is incompatible with your
89 current code and you'll have to change it. Once individual features are
90 stable and no longer declared experimental, they should have the same
91 stability guarantees as any other long-term supported CPAN module, or
92 core Perl itself.
93
94 That all said, please do get in contact if you find the module overall
95 useful. The more feedback you provide in terms of what features you are
96 using, what you find works, and what doesn't, will help the ongoing
97 development and hopefully eventual stability of the design - both
98 within this CPAN module and as the wider experiment to provide it as a
99 core Perl feature. See the "FEEDBACK" section.
100
101 Features of this module that are currently marked as experimental
102 provoke warnings in the experimental category, unless silenced. You can
103 silence this with no warnings 'experimental' but then that will silence
104 every experimental warning, which may hide others unintentionally. For
105 a more fine-grained approach you can instead use the import line for
106 this module to only silence the module's warnings selectively:
107
108 use Object::Pad ':experimental(mop)';
109
110 use Object::Pad ':experimental(custom_field_attr)';
111
112 use Object::Pad ':experimental(composed_adjust)';
113
114 use Object::Pad ':experimental(inherit_field)';
115
116 use Object::Pad ':experimental(apply_phaser)';
117
118 use Object::Pad ':experimental(lexical_class)';
119
120 use Object::Pad ':experimental(:all)'; # all of the above
121
122 Since version 0.64.
123
124 Multiple experimental features can be enabled at once by giving
125 multiple names in the parens, separated by spaces:
126
127 use Object::Pad ':experimental(mop custom_field_attr)';
128
129 Since version 0.810 attempting to request all of the experiments at
130 once by using an empty :experimental() is currently accepted, but
131 yields a warning. This may be removed in future.
132
133 Automatic Construction
134
135 Classes are automatically provided with a constructor method, called
136 new, which helps create the object instances. This may respond to
137 passed arguments, automatically assigning values of fields, and
138 invoking other blocks of code provided by the class. It proceeds in the
139 following stages:
140
141 The BUILDARGS phase
142
143 If the class provides a BUILDARGS class method, that is used to mangle
144 the list of arguments before the BUILD blocks are called. Note this
145 must be a class method not an instance method (and so implemented using
146 sub). It should perform any SUPER chaining as may be required.
147
148 @args = $class->BUILDARGS( @_ )
149
150 Field assignment
151
152 If any field in the class has the :param attribute, then the
153 constructor will expect to receive its argmuents in an even-sized list
154 of name/value pairs. This applies even to fields inherited from the
155 parent class or applied roles. It is therefore a good idea to shape the
156 parameters to the constructor in this way in roles, and in classes if
157 you intend your class to be extended.
158
159 The constructor will also check for required parameters (these are all
160 the parameters for fields that do not have default initialisation
161 expressions). If any of these are missing an exception is thrown.
162
163 The BUILD phase
164
165 As part of the construction process, every BUILD phaser of every
166 component class will be invoked. Each will be passed in the list of
167 arguments the constructor was invoked with as arguments. Each class
168 should perform its required setup behaviour, but does not need to chain
169 to the SUPER class first; this is handled automatically.
170
171 The ADJUST phase
172
173 Next, every ADJUST phaser of every component class is invoked. This
174 happens after the fields are assigned their initial values and the
175 BUILD blocks have been run.
176
177 The strict-checking phase
178
179 Finally, before the object is returned, if the ":strict(params)" class
180 attribute is present, then the constructor will throw an exception if
181 there are any remaining named arguments left over after assigning them
182 to fields as per :param declarations, and running any ADJUST blocks.
183
184 KEYWORDS
185
186 class
187
188 class Name :ATTRS... {
189 ...
190 }
191
192 class Name :ATTRS...;
193
194 Behaves similarly to the package keyword, but provides a package that
195 defines a new class. Such a class provides an automatic constructor
196 method called new.
197
198 As with package, an optional block may be provided. If so, the contents
199 of that block define the new class and the preceding package continues
200 afterwards. If not, it sets the class as the package context of
201 following keywords and definitions.
202
203 As with package, an optional version declaration may be given. If so,
204 this sets the value of the package's $VERSION variable.
205
206 class Name VERSION { ... }
207
208 class Name VERSION;
209
210 An optional list of attributes may be supplied in similar syntax as for
211 subs or lexical variables. (These are annotations about the class
212 itself; the concept should not be confused with per-object-instance
213 data, which here is called "fields").
214
215 Whitespace is permitted within the value and is automatically trimmed,
216 but as standard Perl parsing rules, no space is permitted between the
217 attribute's name and the open parenthesis of its value:
218
219 :attr( value here ) # is permitted
220 :attr (value here) # not permitted
221
222 The following class attributes are supported:
223
224 :isa
225
226 :isa(CLASS)
227
228 :isa(CLASS CLASSVER)
229
230 Since version 0.57.
231
232 Declares a superclass that this class extends. At most one superclass
233 is supported.
234
235 If the package providing the superclass does not exist, an attempt is
236 made to load it by code equivalent to
237
238 require CLASS;
239
240 and thus it must either already exist, or be locatable via the usual
241 @INC mechanisms.
242
243 The superclass may or may not itself be implemented by Object::Pad, but
244 if it is not then see "SUBCLASSING CLASSIC PERL CLASSES" for further
245 detail on the semantics of how this operates.
246
247 An optional version check can also be supplied; it performs the
248 equivalent of
249
250 BaseClass->VERSION( $ver )
251
252 :does
253
254 :does(ROLE)
255
256 :does(ROLE ROLEVER)
257
258 Since version 0.57.
259
260 Composes a role into the class; optionally requiring a version check on
261 the role package.
262
263 Multiple roles can be composed by using multiple :does attributes, one
264 per role.
265
266 The package will be loaded in a similar way to how the ":isa" attribute
267 is handled.
268
269 :abstract
270
271 :abstract
272
273 Since version 0.817.
274
275 Declares that this class is abstract. An abstract class is permitted to
276 define required methods (i.e. named methods without a body definition).
277
278 Instances may not be created of this class type directly. Instead, a
279 subclass of this class must be derived that provides method bodies for
280 any of the named required methods. Any subclass of an abstract class
281 must either provide bodies for all remaining required methods, or
282 themselves be declared :abstract as well.
283
284 This provides a way in which a generic type of class can be created,
285 that is intended for multiple different specialisations to further
286 define different kinds of behaviour by providing bodies for those named
287 methods. Being abstract means that instances cannot be created of this
288 as-yet-incomplete class type.
289
290 :lexical_new
291
292 :lexical_new
293
294 Since version 0.822.
295
296 Causes the constructor for this class to be made available to the class
297 body lexically, and not installed as a symbol in the package's symbol
298 table. The effect of this is that code inside the class can make use of
299 it as a lexical function, but it is not available to callers outside
300 the class. In this way, a wrapper method in the class itself is fully
301 in control of how, and when, instances of the class are constructed.
302
303 For example, a singleton class could be created by providing a wrapper
304 class method that lazily creates a single instance stored in a lexical
305 variable in the class, ensuring every call returns the same instance.
306
307 class A::Singleton :lexical_new {
308 my $instance;
309
310 method instance :common { $instance //= new(shift); }
311
312 ...
313 }
314
315 Note also that since methods are not considered when resolving bareword
316 function call names, it is possible to provide a :common class method
317 called new, which can wrap the default provided constructor. This can
318 be useful for providing a constructor whose arguments are passed in
319 some style other than the usual name/value pairs.
320
321 For example, if a class only has one parameter it is sometimes common
322 style to simply pass that one value as the only constructor parameter.
323
324 class Path :lexical_new {
325 field $filename :param :reader;
326
327 method new :common ($filename) {
328 return &new( $class, filename => $filename );
329 }
330 }
331
332 my $null = Path->new( "/dev/null" );
333
334 Note carefully that to do this you must use method. You cannot use sub
335 here as that will redefine the content of the lexical sub new, rather
336 than creating a new package-named one.
337
338 :repr(TYPE)
339
340 Sets the representation type for instances of this class. Must be one
341 of the following values:
342
343 :repr(native)
344
345 The native representation. This is an opaque representation type whose
346 contents are not specified. It only works for classes whose entire
347 inheritance hierarchy is built only from classes based on Object::Pad.
348
349 :repr(HASH)
350
351 The representation will be a blessed hash reference. The instance data
352 will be stored in an array referenced by a key called
353 Object::Pad/slots, which is fairly unlikely to clash with existing
354 storage on the instance. No other keys will be used; they are available
355 for implementions and subclasses to use. The exact format of the value
356 stored here is not specified and may change between module versions,
357 though it can be relied on to be well-behaved as some kind of perl data
358 structure for purposes of modules like Data::Dumper or serialisation
359 into things like YAML or JSON.
360
361 :repr(keys)
362
363 Since version 0.803.
364
365 The representation will be a blessed hash reference. The instance data
366 will be stored in individual keys of the hash, named after the class
367 and the field variable name, separated by a / symbol. Objects in this
368 representation should behave predictably with data printing modules
369 like Data::Dumper or serialisation via YAML or JSON.
370
371 These two hash-based representation types may be useful when converting
372 existing classes into using Object::Pad where there may be existing
373 subclasses of it that presume a blessed hash for their own use.
374
375 :repr(magic)
376
377 The representation will use MAGIC to apply the instance data in a way
378 that is invisible at the Perl level, and shouldn't get in the way of
379 other things the instance is doing even in XS modules.
380
381 This representation type is the only one that will work for subclassing
382 existing classes that do not use blessed hashes.
383
384 :repr(pvobj)
385
386 Since version 0.804.
387
388 The representation will be the SVt_PVOBJ type newly added to Perl,
389 which offers more efficient storage for object instances. This is only
390 available on Perl version 5.38.0 onwards.
391
392 This is also newly-added and may not be fully tested and reliable yet.
393 Once it has more real-world testing and has proven reliable it may
394 become the default instance representation on versions of Perl where it
395 is available.
396
397 :repr(autoselect), :repr(default)
398
399 Since version 0.23.
400
401 This representation will select one of the representations above
402 depending on what is best for the situation. Classes not derived from a
403 non-Object::Pad base class will pick native, and classes derived from
404 non-Object::Pad bases will pick either the HASH or magic forms
405 depending on whether the instance is a blessed hash reference or some
406 other kind.
407
408 This achieves the best combination of DWIM while still allowing the
409 common forms of hash reference to be inspected by Data::Dumper, etc.
410 This is the default representation type, and does not have to be
411 specifically requested.
412
413 :strict(params)
414
415 Since version 0.43.
416
417 Can only be applied to classes that contain no BUILD phasers. If set,
418 then the constructor will complain about any unrecognised named
419 arguments passed to it (i.e. names that do not correspond to the :param
420 of any defined field and left unconsumed by any ADJUST phaser).
421
422 Since BUILD phasers can inspect the arguments arbitrarily, the presence
423 of any such phaser means the constructor cannot determine which named
424 arguments are not recognised.
425
426 This attribute is a temporary stepping-stone for compatibility with
427 existing code. It is recommended to enable this whenever possible, as a
428 later version of this module will likely perform this behaviour
429 unconditionally whenever no BUILD phasers are present.
430
431 class (anon)
432
433 my $class = class :ATTRS... { ... };
434
435 Since version 0.809.
436
437 If a class keyword is not followed by a package name, it creates an
438 anonymous class expression. This is an expression that yields a value
439 suitable to use as a constructor invocant for creating instances of
440 that class, without specifying what its package name will actually be.
441
442 This is useful for creating small one-off instances inline in
443 expressions, such as in unit tests. Since it still accepts the usual
444 attributes and inner body statements, it can be useful for creating
445 one-off instances of roles, with required methods being applied.
446
447 my $testobj = (class {
448 apply Role::Under::Test;
449 method required { return "a useful value"; }
450 })->new;
451
452 Due to limitations on how classes work in Perl, anonymous classes are
453 still backed by long-lived named classes in the global symbol table,
454 unlike true anonymous functions which can go out of scope and be
455 reclaimed once no references to them remain in existence. This means
456 that anonymous classes will retain references to any variables captured
457 within them, even if the class expression itself goes out of scope and
458 any instances created by it no longer remain.
459
460 role
461
462 role Name :ATTRS... {
463 ...
464 }
465
466 role Name :ATTRS...;
467
468 Since version 0.32.
469
470 Similar to class, but provides a package that defines a new role. A
471 role acts similar to a class in some respects, and differently in
472 others.
473
474 Like a class, a role can have a version, and named methods.
475
476 role Name VERSION {
477 method a { ... }
478 method b { ... }
479 }
480
481 A role does not provide a constructor, and instances cannot directly be
482 constructed. A role cannot extend a class.
483
484 A role can declare that it requires methods of given names from any
485 class that implements the role.
486
487 role Name {
488 requires METHOD;
489 }
490
491 A role can provide instance fields. These are visible to any ADJUST
492 phasers or methods provided by that role.
493
494 Since version 0.33.
495
496 role Name {
497 field $f;
498
499 ADJUST { $f = "a value"; }
500
501 method f { return $f; }
502 }
503
504 Since version 0.57 a role can declare that it provides another role:
505
506 role Name :does(OTHERROLE) { ... }
507 role Name :does(OTHERROLE OTHERVER) { ... }
508
509 This will include all of the methods from the included role.
510 Effectively this means that applying the "outer" role to a class will
511 imply applying the other role as well.
512
513 The following role attributes are supported:
514
515 :compat(invokable)
516
517 Since version 0.35.
518
519 Enables a form of backward-compatibility behaviour useful for gradually
520 upgrading existing code from classical Perl inheritance or mixins into
521 using roles.
522
523 Normally, methods of a role cannot be directly invoked and the role
524 must be applied to an Object::Pad-based class in order to be used. This
525 however presents a problem when gradually upgrading existing code that
526 already uses techniques like roles, multiple inheritance or mixins when
527 that code may be split across multiple distributions, or for some other
528 reason cannot be upgraded all at once. Methods within a role that has
529 the :compat(invokable) attribute applied to it may be directly invoked
530 on any object instance. This allows the creation of a role that can
531 still provide code for existing classes written in classical Perl that
532 has not yet been rewritten to use Object::Pad.
533
534 The tradeoff is that a :compat(invokable) role may not create field
535 data using the "field" keyword. Whatever behaviours the role wishes to
536 perform must be provided only by calling other methods on $self, or
537 perhaps by making assumptions about the representation type of
538 instances.
539
540 It should be stressed again: This option is only intended for gradual
541 upgrade of existing classical Perl code into using Object::Pad. When
542 all existing code is using Object::Pad then this attribute can be
543 removed from the role.
544
545 my class
546
547 my class Name :ATTRS... { ... }
548
549 Since version 0.819; experimental
550
551 If a class keyword is preceded by my it creates a class that has
552 lexical visiblity, rather than being available globally via a
553 fully-qualified name in the symbol table. This is useful for creating
554 internal helper classes within modules, such as for returning complex
555 structures, or simply to use internally without being visible to the
556 caller. As the class itself is only visible lexically, callers in other
557 scopes are unable to see it to create new instances of it.
558
559 class My::Module;
560
561 my class HelperStructure
562 {
563 field $name :param :reader;
564 field $value :param :reader;
565 }
566
567 method get_thing ()
568 {
569 return HelperStructure->new(
570 name => "the name",
571 value => "the value",
572 );
573 }
574
575 Note: the above is technically a lie. Current versions of perl do not
576 support truely anonymous packages to be used as classes, so even these
577 "lexical" classes are in fact named on the symbol table. However, they
578 are given a name that is syntactically-impossible for regular code to
579 create or use, and a const-returning lexical function is created with
580 the correct lexical name, which returns the true name of the class, so
581 that the ->new method can still be called on it.
582
583 As a result of this limitation, there are a number of operations that
584 lexical classes do not currently support - such as subclassing. It is
585 hoped that later versions of either this module, or perl itself, will
586 be able to expand on these abilities. For now, this feature remains an
587 experimental best-effort basis.
588
589 Due to the way this lexical function works, it can stand in for the
590 class name when used with the ->isa method. Note carefully here, that
591 the lexical class is used directly as a bareword and not quoted.
592
593 if( $obj->isa( HelperStructure ) ) { ... }
594
595 Additionally, as the right-hand side operand of the isa operator (in
596 Perl version 5.32 or later) does not need quoting, it can be used there
597 directly:
598
599 if( $obj isa HelperStructure ) { ... }
600
601 inherit
602
603 inherit Classname;
604 inherit Classname VER;
605
606 inherit Classname LIST...;
607 inherit Classname VER LIST...;
608
609 Since version 0.807.
610
611 Declares a superclass that this class extends. At most one superclass
612 is supported. If present, this declaration must come before any methods
613 or fields are declared, or any roles applied. (Other compile-time
614 declarations such as use statements that import utility functions or
615 other behaviours may be permitted before this, however, provided that
616 they do not interact with the class structure in any way).
617
618 This is a newer form of the :isa attribute intended to be more flexible
619 if import arguments or other features are added at a later time.
620
621 If the package providing the superclass does not exist, an attempt is
622 made to load it by code equivalent to
623
624 require Classname;
625
626 and thus it must either already exist, or be locatable via the usual
627 @INC mechanisms.
628
629 An optional version check can also be supplied; it performs the
630 equivalent of
631
632 Classname->VERSION( $ver )
633
634 Experimentally since version 0.807, an optional list of arguments can
635 also be provided, in similar syntax to those in a use statement.
636 Currently this list of arguments must be names of fields to be
637 inherited. Only fields in the base class that are annotated with the
638 :inheritable attribute may be inherited. Once a field is inherited,
639 methods and other expressions in the class body can use that field
640 identically to any fields defined by that class itself.
641
642 class Class1 {
643 field $x :inheritable = 123;
644 }
645
646 class Class2 {
647 inherit Class1 '$x';
648 field $y = 456;
649 method describe { say "Class2(x=$x,y=$y)" }
650 }
651
652 Class2->new->describe;
653
654 apply
655
656 apply Rolename;
657
658 apply Rolename VER;
659
660 Since version 0.807.
661
662 Composes a role into the class; optionally requiring a version check on
663 the role package. This is a newer form of the :does attribute intended
664 to be more flexible if import arguments or other features are added at
665 a later time.
666
667 Multiple roles can be composed by using multiple :does attributes, one
668 per role.
669
670 apply statements can be freely mixed with other statements inside the
671 body of the class. In particular, an apply statement that adds fields
672 or methods may appear before or after the class has defined some of its
673 own. It is not required that they appear first.
674
675 field
676
677 field $var;
678 field @var;
679 field %var;
680
681 field $var :ATTR ATTR...;
682
683 field $var = EXPR;
684
685 field $var //= EXPR;
686 field $var ||= EXPR;
687
688 field $var { BLOCK }
689
690 Since version 0.66.
691
692 Declares that the instances of the class or role have a member field of
693 the given name. This member field will be accessible as a lexical
694 variable within any method declarations and ADJUST phasers in the
695 class.
696
697 Array and hash members are permitted and behave as expected; you do not
698 need to store references to anonymous arrays or hashes.
699
700 Member fields are private to a class or role. They are not visible to
701 users of the class, nor inherited by subclasses nor any class that a
702 role is applied to. In order to provide access to them a class may wish
703 to use "method" to create an accessor, or use the attributes such as
704 ":reader" to get one generated.
705
706 The following field attributes are supported:
707
708 :reader, :reader(NAME)
709
710 Since version 0.27.
711
712 Generates a reader method to return the current value of the field. If
713 no name is given, the name of the field is used. A single prefix
714 character _ will be removed if present.
715
716 field $x :reader;
717
718 # equivalent to
719 field $x; method x { return $x }
720
721 Since version 0.55 these are permitted on any field type, but prior
722 versions only allowed them on scalar fields. The reader method behaves
723 identically to how a lexical variable would behave in the same context;
724 namely returning a list of values from an array or key/value pairs from
725 a hash when in list context, or the number of items or keys when in
726 scalar context.
727
728 field @items :reader;
729
730 foreach my $item ( $obj->items ) { ... } # iterates the list of items
731
732 my $count = $obj->items; # yields count of items
733
734 :writer, :writer(NAME)
735
736 Since version 0.27.
737
738 Generates a writer method to set a new value of the field from its
739 arguments. If no name is given, the name of the field is used prefixed
740 by set_. A single prefix character _ will be removed if present.
741
742 field $x :writer;
743
744 # equivalent to
745 field $x; method set_x { $x = shift; return $self }
746
747 Since version 0.28 a generated writer method will return the object
748 invocant itself, allowing a chaining style.
749
750 $obj->set_x("x")
751 ->set_y("y")
752 ->set_z("z");
753
754 Since version 0.55 these are permitted on any field type, but prior
755 versions only allowed them on scalar fields. On arrays or hashes, the
756 writer method takes a list of values to be assigned into the field,
757 completely replacing any values previously there.
758
759 :mutator, :mutator(NAME)
760
761 Since version 0.27.
762
763 Generates an lvalue mutator method to return or set the value of the
764 field. These are only permitted for scalar fields. If no name is given,
765 the name of the field is used. A single prefix character _ will be
766 removed if present.
767
768 field $x :mutator;
769
770 # equivalent to
771 field $x; method x :lvalue { $x }
772
773 Since version 0.28 all of these generated accessor methods will include
774 argument checking similar to that used by subroutine signatures, to
775 ensure the correct number of arguments are passed - usually zero, but
776 exactly one in the case of a :writer method.
777
778 :accessor, :accessor(NAME)
779
780 Since version 0.53.
781
782 Generates a combined reader-writer accessor method to set or return the
783 value of the field. These are only permitted for scalar fields. If no
784 name is given, the name of the field is used. A prefix character _ will
785 be removed if present.
786
787 This method takes either zero or one additional arguments. If an
788 argument is passed, the value of the field is set from this argument
789 (even if it is undef). If no argument is passed (i.e. scalar @_ is
790 false) then the field is not modified. In either case, the value of the
791 field is then returned.
792
793 field $x :accessor;
794
795 # equivalent to
796 field $x;
797
798 method x {
799 $x = shift if @_;
800 return $x;
801 }
802
803 :weak
804
805 Since version 0.44.
806
807 Generated code which sets the value of this field will weaken it if it
808 contains a reference. This applies to within the constructor if :param
809 is given, and to a :writer accessor method. Note that this only applies
810 to automatically generated code; not normal code written in regular
811 method bodies. If you assign into the field variable you must remember
812 to call Scalar::Util::weaken (or builtin::weaken on Perl 5.36 or above)
813 yourself.
814
815 :param, :param(NAME)
816
817 Since version 0.41.
818
819 Sets this field to be initialised automatically in the generated
820 constructor. This is only permitted on scalar fields. If no name is
821 given, the name of the field is used. A single prefix character _ will
822 be removed if present.
823
824 Any field that has :param but does not have a default initialisation
825 expression or block becomes a required argument to the constructor.
826 Attempting to invoke the constructor without a named argument for this
827 will throw an exception. In order to make a parameter optional, make
828 sure to give it a default expression - even if that expression is
829 undef:
830
831 field $x :param; # this is required
832 field $z :param = undef; # this is optional
833
834 Any field that has a :param and an initialisation block will only run
835 the code in the block if required by the constructor. If a named
836 parameter is passed to the constructor for this field, then its code
837 block will not be executed.
838
839 Values for fields are assigned by the constructor before any BUILD
840 phasers are invoked.
841
842 :inheritable
843
844 Experimentally since version 0.807 fields may be optionally inherited
845 when deriving a subclass from another. Not every field is allowed to be
846 inherited. This attribute marks a field as being available for
847 subclasses to inherit.
848
849 Field Initialiser Expressions
850
851 Since version 0.54 a deferred statement block is also permitted, on any
852 field variable type. This permits code to be executed as part of the
853 instance constructor, rather than running just once when the class is
854 set up. Code in a field initialisation block is roughly equivalent to
855 being placed in a BUILD or ADJUST phaser.
856
857 Since version 0.73 this may also be written as a plain expression
858 introduced by an equals symbol (=). This is equivalent to using a
859 block. Note carefully: the equals symbol is part of the field syntax;
860 it is not simply a runtime assignment operator that happens once at the
861 time the class is declared. Just like the block form describe above,
862 the expression is evaluated during the constructor of every instance.
863
864 Since version 0.74 this expression may also be written using a
865 defined-or or logical-or assignment operator (//= or ||=). In these
866 case, the default expression will be evaluated and assigned if the
867 caller did not pass a value to the constructor at all, or if the value
868 passed was undef (for //=) or false (for ||=). For most scalar
869 parameters, where undef is not a valid value, you probably wanted to
870 use //= to assign defaults.
871
872 class Action {
873 field $timeout :param //= 20;
874 ...
875 }
876
877 # The default of 20 will apply here too
878 my $act = Action->new( timeout => $opts{timeout} );
879
880 Note that $self is specifically not visible during an initialiser
881 expression. This is because the object is not yet fully constructed, so
882 it would be dangerous to allow access to it while in this state.
883 However, the __CLASS__ keyword is available, so initialiser expressions
884 can make use of class-based dispatch to invoke class-level methods to
885 help provide values.
886
887 Field initialier expressions were originally experimental, but since
888 version 0.800 no longer emit experimental warnings.
889
890 Since version 0.806 fields already declared in a class are visible
891 during the initialisation expression of later fields, and their
892 assigned value can be used here. If the earlier field had a :param
893 declaration, it will have been assigned from the value passed to the
894 constructor. Note however that all ADJUST phasers happen after field
895 initialisation expressions, so any modified values set in such phasers
896 will not be visible at this time.
897
898 Control flow that attempts to leave a field initialiser expression or
899 block is not permitted. This includes any return expression, any
900 next/last/redo outside of a loop, with a dynamically-calculated label
901 expression, or with a label that it doesn't appear in. goto statements
902 are also currently forbidden, though known-safe ones may be permitted
903 in future.
904
905 Loop control expressions that are known at compiletime to affect a loop
906 that they appear within are permitted.
907
908 field $x { foreach(@list) { next; } } # this is fine
909
910 field $x { LOOP: while(1) { last LOOP; } } # this is fine too
911
912 has
913
914 Since version 0.813 this keyword is no longer recognised.
915
916 It used to be an earlier version of what is now the "field" keyword.
917
918 has $var;
919 has @var;
920 has %var;
921
922 has $var = EXPR;
923
924 has $var { BLOCK }
925
926 Because of the one-shot immediate nature of these initialisation
927 expressions (and a bunch of other reasons), the keyword was removed.
928
929 If you need to evaluate an expression exactly once during the class
930 declaration and assign its now-constant value to every instace, store
931 it in a regular my variable instead:
932
933 my $default_var = EXPR;
934 field $var = $default_var;
935
936 method
937
938 method NAME {
939 ...
940 }
941
942 method NAME (SIGNATURE) {
943 ...
944 }
945
946 method NAME :ATTRS... {
947 ...
948 }
949
950 method NAME;
951
952 Declares a new named method. This behaves similarly to the sub keyword,
953 except that within the body of the method all of the member fields are
954 also accessible. In addition, the method body will have a lexical
955 called $self which contains the invocant object directly; it will
956 already have been shifted from the @_ array.
957
958 If the method has no body and is given simply as a name, this declares
959 a required method for a role or abstract class. Such a method must be
960 provided by any class that wishes to be non-abstract. It will be a
961 compiletime error to apply the role to a class, or derive from an
962 abstract class, that does not provide this.
963
964 The signatures feature is automatically enabled for method
965 declarations. In this case the signature does not have to account for
966 the invocant instance; that is handled directly.
967
968 method m ($one, $two) {
969 say "$self invokes method on one=$one two=$two";
970 }
971
972 ...
973 $obj->m(1, 2);
974
975 A list of attributes may be supplied as for sub. The most useful of
976 these is :lvalue, allowing easy creation of read-write accessors for
977 fields (but see also the :reader, :writer and :mutator field
978 attributes).
979
980 class Counter {
981 field $count;
982
983 method count :lvalue { $count }
984 }
985
986 my $c = Counter->new;
987 $c->count++;
988
989 Every method automatically gets the :method attribute applied, which
990 suppresses warnings about ambiguous calls resolved to core functions if
991 the name of a method matches a core function.
992
993 The following additional attributes are recognised by Object::Pad
994 directly:
995
996 :override
997
998 Since version 0.29.
999
1000 Marks that this method expects to override another of the same name
1001 from a superclass. It is an error at compiletime if the superclass does
1002 not provide such a method.
1003
1004 :common
1005
1006 Since version 0.62.
1007
1008 Marks that this method is a class-common method, instead of a regular
1009 instance method. A class-common method may be invoked on class names
1010 instead of instances. Within the method body there is a lexical $class
1011 available, rather than $self. Because it is not associated with a
1012 particular object instance, a class-common method cannot see instance
1013 fields.
1014
1015 method (lexical)
1016
1017 method $var { ... }
1018
1019 method $var :ATTRS... (SIGNATURE) { ... }
1020
1021 Since version 0.59.
1022
1023 Declares a new lexical method. Lexical methods are not visible via the
1024 package namespace, but instead are stored directly in a lexical
1025 variable (with the same scoping rules as regular my variables). These
1026 can be invoked by subsequent method code in the same block by using
1027 $self->$var(...) method call syntax.
1028
1029 class WithPrivate {
1030 field $var;
1031
1032 # Lexical methods can still see instance fields as normal
1033 method $inc_var { $var++; say "Var was incremented"; }
1034 method $dec_var { $var--; say "Var was decremented"; }
1035
1036 method bump {
1037 $self->$inc_var;
1038 say "In the middle";
1039 $self->$dec_var;
1040 }
1041 }
1042
1043 my $obj = WithPrivate->new;
1044
1045 $obj->bump;
1046
1047 # Neither $inc_var nor $dec_var are visible here
1048
1049 This effectively provides the ability to define private methods, as
1050 they are inaccessible from outside the block that defines the class. In
1051 addition, there is no chance of a name collision because lexical
1052 variables in different scopes are independent, even if they share the
1053 same name. This is particularly useful in roles or abstract base
1054 classes, to create internal helper methods without letting those
1055 methods be visible to callers, or risking their names colliding with
1056 other named methods defined on the consuming class.
1057
1058 my method
1059
1060 my method NAME { ... }
1061
1062 Since version 0.814 lexical method declarations are supported using the
1063 my keyword prefix. These become available as lexical functions, rather
1064 than being stored in the class package. As a result, they are not
1065 available by named method resolution, package ->can lookup, or via the
1066 MOP. These are a convenient alternative to the syntax given above,
1067 where the method is stored anonymously via a lexical variable.
1068
1069 Since lexical methods are not visible to named method resolution, they
1070 must be invoked by function-call syntax, remembering to pass in the
1071 invocant as the first argument:
1072
1073 my method inner { ... }
1074
1075 method outer {
1076 inner($self, @args);
1077 }
1078
1079 BUILD
1080
1081 BUILD {
1082 ...
1083 }
1084
1085 BUILD (SIGNATURE) {
1086 ...
1087 }
1088
1089 Since version 0.27.
1090
1091 Declares a builder phaser for this component class. A builder phaser
1092 may use subroutine signature syntax, as for methods, to assist in
1093 unpacking its arguments. A build phaser is not a subroutine and thus is
1094 not permitted to use subroutine attributes (for example :lvalue).
1095
1096 Note that a BUILD phaser is a named phaser block and not a method.
1097 Attempts to create a method named BUILD (i.e. with syntax method BUILD
1098 {...}) will fail with a compiletime error, to avoid this confusion.
1099
1100 ADJUST
1101
1102 ADJUST {
1103 ...
1104 }
1105
1106 Since version 0.43.
1107
1108 Declares an adjust phaser for this component class. This block of code
1109 runs within the constructor, after any BUILD phasers and automatic
1110 field value assignment. It can make any final adjustments to the
1111 instance (such as initialising fields from calculated values).
1112
1113 An adjust phaser is not a subroutine and thus is not permitted to use
1114 subroutine attributes (except see below). Note that an ADJUST phaser is
1115 a named phaser block and not a method; it does not use the sub or
1116 method keyword. But, like with method, the member fields are accessible
1117 within the code body, as is the special $self lexical.
1118
1119 Currently, an ADJUST phaser receives a reference to the hash containing
1120 the current constructor arguments, as per "ADJUSTPARAMS" (see below).
1121 This was added in version 0.66 but will be removed again as it
1122 conflicts with the more flexible and generally nicer named-parameter
1123 ADJUST :params syntax (see below). Such uses should be considered
1124 deprecated. A warning will be printed to indicate this whenever an
1125 ADJUST phaser uses a signature. This warning can be quieted by using
1126 ADJUSTPARAMS instead. Additionally, a warning may be printed on code
1127 that attempts to access the params hashref via the @_ array.
1128
1129 Since version 0.801 in a future version of this module, ADJUST phasers
1130 may be implemented as true blocks and will not permit out-of-block
1131 control flow. At present, they are implemented as one full CV per
1132 block, but a warning is emitted if out-of-block control flow is
1133 attempted.
1134
1135 ADJUST {
1136 return;
1137 }
1138
1139 Using return to leave an ADJUST phaser is discouraged and will be removed
1140 in a later version at FILE line LINE.
1141
1142 Since version 0.805 an experimental feature can be enabled that puts
1143 all the ADJUST phasers into a single CV, rather than creating one CV
1144 for every phaser. This is currently being tested for stability, and may
1145 become the default behaviour in a future version. For now it must be
1146 requested specially:
1147
1148 use Object::Pad ':experimental(composed_adjust)';
1149
1150 ADJUST :params
1151
1152 ADJUST :params ( :$var1, :$var2, ... ) {
1153 ...
1154 }
1155
1156 ADJUST :params ( :$var1, :$var2, ..., %varN ) {
1157 ...
1158 }
1159
1160 Since version 0.70; non-experimental since version 0.805.
1161
1162 An ADJUST phaser can marked with a :params attribute, meaning that it
1163 consumes additional constructor parameters by assigning them into
1164 lexical variables.
1165
1166 Before the phaser itself, a list of lexical variables are introduced,
1167 inside parentheses. The name of each one is preceded by a colon, and
1168 consumes a constructor parameter of the same name. These parameters are
1169 considered "consumed" for the purposes of a :strict(params) check.
1170
1171 A named parameter may be provided with default expression, which is
1172 evaluated if no matching named argument is provided to the constructor.
1173 As with fields, if a named parameter has no defaulting expression it
1174 becomes a required argument to the constructor; an exception is thrown
1175 by the constructor if it absent.
1176
1177 For example,
1178
1179 ADJUST :params ( :$x, :$y = "default", :$z ) { ... }
1180
1181 Note here that x and z are required parameters for the constructor of a
1182 class containing this phaser, but y is an optional parameter whose
1183 value will be filled in by the expression if not provided. Because
1184 these parameters are named and not positional, there is no ordering
1185 constraint; required and optional parameters can be freely mixed.
1186
1187 Optional parameters can also use the //= and ||= operators to provide a
1188 default expression. In these cases, the default will be applied if the
1189 caller did not provide the named argument at all, or if the provided
1190 value was not defined (for //=) or not true (for ||=).
1191
1192 ADJUST :params ( :$name //= "unnamed" ) { ... }
1193
1194 Like with subroutine signature parameters, every declared named
1195 parameter is visible to the defaulting expression of all the later
1196 ones. This permits values to be calculated based on other ones. For
1197 example,
1198
1199 ADJUST :params ( :$thing = undef, :$things = [ $thing ] ) {
1200 # Here, @$things is a list of values
1201 }
1202
1203 This permits the caller to pass a list of values via an array reference
1204 in the things parameter, or a single value in thing.
1205
1206 The final element may be a regular hash variable. This requests that
1207 all remaining named parameters are made available inside it. The code
1208 in the phaser should delete from this hash any parameters it wishes to
1209 consume, as with the earlier case above.
1210
1211 It is unspecified whether named fields or parameters for subclasses yet
1212 to be processed are visible to hashes of earlier superclasses. In the
1213 current implementation they are, but code should not rely on this fact.
1214
1215 Note also that there must be a space between the :params attribute and
1216 the parentheses holding the named parameters. If this space is not
1217 present, perl will parse the parentheses as if they are the value to
1218 the :params() attribute, and this will fail to parse as intended. As
1219 with other attributes and subroutine signatures, this whitespace is
1220 significant.
1221
1222 (This notation is borrowed from a plan to add named parameter support
1223 to perl's subroutine signature syntax).
1224
1225 ADJUSTPARAMS
1226
1227 Since version 0.51.
1228
1229 ADJUSTPARAMS ( $params ) { # on perl 5.26 onwards
1230 ...
1231 }
1232
1233 ADJUST {
1234 my $params = shift;
1235 ...
1236 }
1237
1238 A variant of an ADJUST phaser that receives a reference to the hash
1239 containing the current constructor parameters. This hash will not
1240 contain any constructor parameters already consumed by ":param"
1241 declarations on any fields, but only the leftovers once those are
1242 processed.
1243
1244 The code in the phaser should delete from this hash any parameters it
1245 wishes to consume. Once all the ADJUST phasers have run, any remaining
1246 keys in the hash will be considered errors, subject to the
1247 ":strict(params)" check.
1248
1249 APPLY
1250
1251 Experimental. Since version 0.815.
1252
1253 APPLY ( $class_mop ) { # on perl 5.26 onwards
1254 ...
1255 }
1256
1257 APPLY {
1258 my $class_mop = shift;
1259 ...
1260 }
1261
1262 Only valid within a role definition. Declares a block of code that will
1263 be run at compile-time whenever the role is applied to a class. Each
1264 time it is applied to a new class, the code will be invoked. It
1265 receives as an argument a Object::Pad::MOP::Class instance representing
1266 the class to which the role is currently being applied.
1267
1268 The eventual intent is that the presence of any of these phaser blocks
1269 will replace the current implicit behaviour of applying a role, though
1270 currently they run in addition to it. This is part of an ongoing
1271 experiment whose details will change over time.
1272
1273 __CLASS__
1274
1275 my $classname = __CLASS__;
1276
1277 Since version 0.72.
1278
1279 Only valid within the body (or signature) of a method, an ADJUST
1280 phaser, or the initialising expression of a field. Yields the class
1281 name of the instance that the method, block or expression is invoked
1282 on.
1283
1284 This is similar to the core perl __PACKAGE__ constant, except that it
1285 cares about the dynamic class of the actual instance, not the static
1286 class the code belongs to. When invoked by a subclass instance that
1287 inherited code from its superclass it yields the name of the class of
1288 the instance regardless of which class defined the code.
1289
1290 For example,
1291
1292 class BaseClass {
1293 ADJUST { say "Constructing an instance of " . __CLASS__; }
1294 }
1295
1296 class DerivedClass :isa(BaseClass) { }
1297
1298 my $obj = DerivedClass->new;
1299
1300 Will produce the following output
1301
1302 Constructing an instance of DerivedClass
1303
1304 This is particularly useful in field initialisers for invoking
1305 (constant) methods on the invoking class to provide default values for
1306 fields. This way a subclass could provide a different value.
1307
1308 class Timer {
1309 use constant DEFAULT_DURATION => 60;
1310 field $duration = __CLASS__->DEFAULT_DURATION;
1311 }
1312
1313 class ThreeMinuteTimer :isa(Timer) {
1314 use constant DEFAULT_DURATION => 3 * 60;
1315 }
1316
1317 requires
1318
1319 requires NAME;
1320
1321 Declares that this role requires a method of the given name from any
1322 class that implements it. It is an error at compiletime if the
1323 implementing class does not provide such a method.
1324
1325 This form of declaring a required method is now vaguely discouraged, in
1326 favour of the bodyless method form described above.
1327
1328 CREPT FEATURES
1329
1330 While not strictly part of being an object system, this module has
1331 nevertheless gained a number of behaviours by feature creep, as they
1332 have been found useful.
1333
1334 Implied Pragmata
1335
1336 In order to encourage users to write clean, modern code, the body of
1337 the class block might act as if the following pragmata are in effect:
1338
1339 use strict;
1340 use warnings;
1341 no indirect ':fatal'; # or no feature 'indirect' on perl 5.32 onwards
1342 use feature 'signatures';
1343
1344 This behaviour was designed early around the original "line-0" version
1345 of the Perl 7 plan, which has subsequently been found to be a bad
1346 design and abandoned. That leaves this module in an unfortunate
1347 situation, because its behaviour here does not match the plans for core
1348 perl; where the recently-added class keyword does none of this,
1349 although the method keyword always behaves as if signatures were
1350 enabled anyway.
1351
1352 If you import this module with a module version number of 0.821 or
1353 higher, this behaviour will not happen. This will be the default
1354 behaviour in future versions, and matches how the core perl feature
1355 works. (Though method will still always parse as if the signatures
1356 feature is enabled.) In particular, this no longer applies a catch-all
1357 use warnings, meaning that any prior declarations of use experimental
1358 or no warnings 'experimental::...' will not be overridden.
1359
1360 However, in order to not upset older code that may have relied on these
1361 pragmata being present, module imports without such a version number
1362 will still enable them. This ensures that code not yet updated for the
1363 version 0.821 semantics is not affected.
1364
1365 In addition, if you import this module with a module version number of
1366 0.800 or higher (but less than 0.821) it will emit a warning if you
1367 forget to enable strict and warnings before using the class or role
1368 keywords:
1369
1370 use Object::Pad 0.800;
1371
1372 class X { ... }
1373
1374
1375 class keyword enabled 'use strict' but this will be removed in a later version at FILE line 3.
1376 class keyword enabled 'use warnings' but this will be removed in a later version at FILE line 3.
1377
1378 For newly-written code in a modern style, remember that a handy way to
1379 enable the strict and warnings pragmata for the entire file at once is
1380 to use the use VERSION syntax at the top of the file. A requested
1381 version of v5.36 or later will already perform all of the pragmata
1382 listed above.
1383
1384 use v5.36;
1385
1386 Yield True
1387
1388 The following behaviour is likely to be removed in a later version of
1389 this module.
1390
1391 A class statement or block will yield a true boolean value. This means
1392 that it can be used directly inside a .pm file, avoiding the need to
1393 explicitly yield a true value from the end of it.
1394
1395 As with the implied pragmata above, this behaviour has also been found
1396 to be a bad design and will likely be removed soon. For now it is
1397 suggested not to rely on it and instead either use the new module_true
1398 feature already part of the use v5.38 pragma, or on older perls simply
1399 remember to put an explicit true value at the end of the file.
1400
1401 SUBCLASSING CLASSIC PERL CLASSES
1402
1403 There are a number of details specific to the case of deriving an
1404 Object::Pad class from an existing classic Perl class that is not
1405 implemented using Object::Pad.
1406
1407 Storage of Instance Data
1408
1409 Instances will pick either the :repr(HASH) or :repr(magic) storage
1410 type.
1411
1412 Object State During Methods Invoked By Superclass Constructor
1413
1414 It is common in classic Perl OO style to invoke methods on $self during
1415 the constructor. This is supported here since Object::Pad version 0.19.
1416 Note however that any methods invoked by the superclass constructor may
1417 not see the object in a fully consistent state. (This fact is not
1418 specific to using Object::Pad and would happen in classic Perl OO as
1419 well). The field initialisers will have been invoked but the BUILD and
1420 ADJUST phasers will not.
1421
1422 For example; in the following
1423
1424 package ClassicPerlBaseClass {
1425 sub new {
1426 my $self = bless {}, shift;
1427 say "Value seen by superconstructor is ", $self->get_value;
1428 return $self;
1429 }
1430 sub get_value { return "A" }
1431 }
1432
1433 class DerivedClass :isa(ClassicPerlBaseClass) {
1434 field $_value = "B";
1435 ADJUST {
1436 $_value = "C";
1437 }
1438 method get_value { return $_value }
1439 }
1440
1441 my $obj = DerivedClass->new;
1442 say "Value seen by user is ", $obj->get_value;
1443
1444 Until the ClassicPerlBaseClass::new superconstructor has returned the
1445 ADJUST phaser will not have been invoked. The $_value field will still
1446 exist, but its value will be B during the superconstructor. After the
1447 superconstructor, the BUILD and ADJUST phasers are invoked before the
1448 completed object is returned to the user. The result will therefore be:
1449
1450 Value seen by superconstructor is B
1451 Value seen by user is C
1452
1453 STYLE SUGGESTIONS
1454
1455 While in no way required, the following suggestions of code style
1456 should be noted in order to establish a set of best practices, and
1457 encourage consistency of code which uses this module.
1458
1459 $VERSION declaration
1460
1461 While it would be nice for CPAN and other toolchain modules to parse
1462 the embedded version declarations in class statements, the current
1463 state at time of writing (June 2020) is that none of them actually do.
1464 As such, it will still be necessary to make a once-per-file $VERSION
1465 declaration in syntax those modules can parse.
1466
1467 Further note that these modules will also not parse the class
1468 declaration, so you will have to duplicate this with a package
1469 declaration as well as a class keyword. This does involve repeating the
1470 package name, so is slightly undesirable.
1471
1472 It is hoped that eventually upstream toolchain modules will be adapted
1473 to accept the class syntax as being sufficient to declare a package and
1474 set its version.
1475
1476 See also
1477
1478 * https://github.com/Perl-Toolchain-Gang/Module-Metadata/issues/33
1479
1480 File Layout
1481
1482 Begin the file with a use Object::Pad line; ideally including a
1483 minimum-required version. This should be followed by the toplevel
1484 package and class declarations for the file. As it is at toplevel there
1485 is no need to use the block notation; it can be a unit class.
1486
1487 There is no need to use strict or apply other usual pragmata; these
1488 will be implied by the class keyword.
1489
1490 use Object::Pad 0.16;
1491
1492 package My::Classname 1.23;
1493 class My::Classname;
1494
1495 # other use statements
1496
1497 # field, methods, etc.. can go here
1498
1499 Field Names
1500
1501 Field names should follow similar rules to regular lexical variables in
1502 code - lowercase, name components separated by underscores. For tiny
1503 examples such as "dumb record" structures this may be sufficient.
1504
1505 class Tag {
1506 field $name :mutator;
1507 field $value :mutator;
1508 }
1509
1510 In larger examples with lots of non-trivial method bodies, it can get
1511 confusing to remember where the field variables come from (because we
1512 no longer have the $self->{ ... } visual clue). In these cases it is
1513 suggested to prefix the field names with a leading underscore, to make
1514 them more visually distinct.
1515
1516 class Spudger {
1517 field $_grapefruit;
1518
1519 ...
1520
1521 method mangle {
1522 $_grapefruit->peel; # The leading underscore reminds us this is a field
1523 }
1524 }
1525
1526 WITH OTHER MODULES
1527
1528 Syntax::Keyword::Dynamically
1529
1530 A cross-module integration test asserts that dynamically works
1531 correctly on object instance fields:
1532
1533 use Object::Pad;
1534 use Syntax::Keyword::Dynamically;
1535
1536 class Container {
1537 field $value = 1;
1538
1539 method example {
1540 dynamically $value = 2;
1541 ,..
1542 # value is restored to 1 on return from this method
1543 }
1544 }
1545
1546 Future::AsyncAwait
1547
1548 As of Future::AsyncAwait version 0.38 and Object::Pad version 0.15,
1549 both modules now use XS::Parse::Sublike to parse blocks of code.
1550 Because of this the two modules can operate together and allow class
1551 methods to be written as async subs which await expressions:
1552
1553 use Future::AsyncAwait;
1554 use Object::Pad;
1555
1556 class Example
1557 {
1558 async method perform ($block)
1559 {
1560 say "$self is performing code";
1561 await $block->();
1562 say "code finished";
1563 }
1564 }
1565
1566 These three modules combine; there is additionally a cross-module test
1567 to ensure that object instance fields can be dynamically set during a
1568 suspended async method.
1569
1570 Devel::MAT
1571
1572 When using Devel::MAT to help analyse or debug memory issues with
1573 programs that use Object::Pad, you will likely want to additionally
1574 install the module Devel::MAT::Tool::Object::Pad. This will provide new
1575 commands and extend existing ones to better assist with analysing
1576 details related to Object::Pad classes and instances of them.
1577
1578 pmat> fields 0x55d7c173d4b8
1579 The field AV ARRAY(3)=NativeClass at 0x55d7c173d4b8
1580 Ix Field Value
1581 0 $sfield SCALAR(UV) at 0x55d7c173d938 = 123
1582 ...
1583
1584 pmat> identify 0x55d7c17606d8
1585 REF() at 0x55d7c17606d8 is:
1586 └─the %hfield field of ARRAY(3)=NativeClass at 0x55d7c173d4b8, which is:
1587 ...
1588
1589 DESIGN TODOs
1590
1591 The following points are details about the design of pad field-based
1592 object systems in general:
1593
1594 * Is multiple inheritance actually required, if role composition is
1595 implemented including giving roles the ability to use private fields?
1596
1597 * Consider the visibility of superclass fields to subclasses. Do
1598 subclasses even need to be able to see their superclass's fields, or
1599 are accessor methods always appropriate?
1600
1601 Concrete example: The $self->{split_at} access that
1602 Tickit::Widget::HSplit makes of its parent class
1603 Tickit::Widget::LinearSplit.
1604
1605 IMPLEMENTATION TODOs
1606
1607 These points are more about this particular module's implementation:
1608
1609 * Consider multiple inheritance of subclassing, if that is still
1610 considered useful after adding roles.
1611
1612 * Work out why no indirect doesn't appear to work properly before
1613 perl 5.20.
1614
1615 * Work out why we don't get a Subroutine new redefined at ... warning
1616 if we
1617
1618 sub new { ... }
1619
1620 * The local modifier does not work on field variables, because they
1621 appear to be regular lexicals to the parser at that point. A
1622 workaround is to use Syntax::Keyword::Dynamically instead:
1623
1624 use Syntax::Keyword::Dynamically;
1625
1626 field $loglevel;
1627
1628 method quietly {
1629 dynamically $loglevel = LOG_ERROR;
1630 ...
1631 }
1632
1633 FEEDBACK
1634
1635 The following resources are useful forms of providing feedback,
1636 especially in the form of reports of what you find good or bad about
1637 the module, requests for new features, questions on best practice,
1638 etc...
1639
1640 * The RT queue at
1641 https://rt.cpan.org/Dist/Display.html?Name=Object-Pad.
1642
1643 * The #cor IRC channel on irc.perl.org.
1644
1645 SPONSORS
1646
1647 With thanks to the following sponsors, who have helped me be able to
1648 spend time working on this module and other perl features.
1649
1650 * Oetiker+Partner AG https://www.oetiker.ch/en/
1651
1652 * Deriv http://deriv.com
1653
1654 * Perl-Verein Schweiz https://www.perl-workshop.ch/
1655
1656 Additional details may be found at
1657 https://github.com/Ovid/Cor/wiki/Sponsors.
1658
1659 AUTHOR
1660
1661 Paul Evans <[email protected]>
1662