1Object::Pad(3) User Contributed Perl Documentation Object::Pad(3)
2
3
4
6 "Object::Pad" - a simple syntax for lexical slot-based objects
7
9 use Object::Pad;
10
11 class Point {
12 has $x = 0;
13 has $y = 0;
14
15 BUILD {
16 ($x, $y) = @_;
17 }
18
19 method move ($dX, $dY) {
20 $x += $dX;
21 $y += $dY;
22 }
23
24 method describe {
25 print "A point at ($x, $y)\n";
26 }
27 }
28
29 Point->new(5,10)->describe;
30
32 This module provides a simple syntax for creating object classes, which
33 uses private variables that look like lexicals as object member fields.
34
35 WARNING This module is still very experimental. The parts that
36 currently exist do seem to work reliably but much of the design is
37 still evolving, and many features and have yet to be implemented. I
38 don't yet guarantee I won't have to change existing details in order to
39 continue its development. Feel free to try it out in experimental or
40 newly-developed code, but don't complain if a later version is
41 incompatible with your current code and you'll have to change it.
42
43 That all said, please do get in contact if you find the module overall
44 useful. The more feedback you provide in terms of what features you
45 are using, what you find works, and what doesn't, will help the ongoing
46 development and hopefully eventual stability of the design. See the
47 "FEEDBACK" section.
48
49 Automatic Construction
50 Classes are automatically provided with a constructor method, called
51 "new", which helps create the object instances.
52
53 As part of the construction process, the "BUILD" block of every
54 component class will be invoked, passing in the list of arguments the
55 constructor was invoked with. Each class should perform its required
56 setup behaviour, but does not need to chain to the "SUPER" class first;
57 this is handled automatically.
58
59 If the class provides a "BUILDARGS" class method, that is used to
60 mangle the list of arguments before the "BUILD" blocks are called. Note
61 this must be a class method not an instance method (and so implemented
62 using "sub"). It should perform any "SUPER" chaining as may be
63 required.
64
65 @args = $class->BUILDARGS( @_ )
66
68 class
69 class Name :ATTRS... {
70 ...
71 }
72
73 class Name :ATTRS...;
74
75 Behaves similarly to the "package" keyword, but provides a package that
76 defines a new class. Such a class provides an automatic constructor
77 method called "new".
78
79 As with "package", an optional block may be provided. If so, the
80 contents of that block define the new class and the preceding package
81 continues afterwards. If not, it sets the class as the package context
82 of following keywords and definitions.
83
84 As with "package", an optional version declaration may be given. If so,
85 this sets the value of the package's $VERSION variable.
86
87 class Name VERSION { ... }
88
89 class Name VERSION;
90
91 A single superclass is supported by the keyword "extends"
92
93 class Name extends BASECLASS {
94 ...
95 }
96
97 class Name extends BASECLASS BASEVER {
98 ...
99 }
100
101 If a package providing the superclass does not exist, an attempt is
102 made to load it by code equivalent to
103
104 require Animal ();
105
106 and thus it must either already exist, or be locatable via the usual
107 @INC mechanisms.
108
109 The superclass may or may not itself be implemented by "Object::Pad",
110 but if it is not then see "SUBCLASSING CLASSIC PERL CLASSES" for
111 further detail on the semantics of how this operates.
112
113 An optional version check can also be supplied; it performs the
114 equivalent of
115
116 BaseClass->VERSION( $ver )
117
118 One or more roles can be composed into the class by the keyword
119 "implements"
120
121 class Name implements ROLE, ROLE,... {
122 ...
123 }
124
125 An optional list of attributes may be supplied in similar syntax as for
126 subs or lexical variables. (These are annotations about the class
127 itself; the concept should not be confused with per-object-instance
128 data, which here is called "slots"). The following class attributes are
129 supported:
130
131 :repr(TYPE)
132
133 Sets the representation type for instances of this class. Must be one
134 of the following values:
135
136 :repr(native)
137
138 The native representation. This is an opaque representation type whose
139 contents are not specified. It only works for classes whose entire
140 inheritence hierarchy is built only from classes based on
141 "Object::Pad".
142
143 :repr(HASH)
144
145 The representation will be a blessed hash reference. The instance data
146 will be stored in an array referenced by a key called
147 "Object::Pad/slots", which is fairly unlikely to clash with existing
148 storage on the instance. No other keys will be used; they are available
149 for implementions and subclasses to use. The exact format of the value
150 stored here is not specified and may change between module versions,
151 though it can be relied on to be well-behaved as some kind of perl data
152 structure for purposes of modules like Data::Dumper or serialisation
153 into things like "YAML" or "JSON".
154
155 This representation type may be useful when converting existing classes
156 into using "Object::Pad" where there may be existing subclasses of it
157 that presume a blessed hash for their own use.
158
159 :repr(magic)
160
161 The representation will use MAGIC to apply the instance data in a way
162 that is invisible at the Perl level, and shouldn't get in the way of
163 other things the instance is doing even in XS modules.
164
165 This representation type is the only one that will work for subclassing
166 existing classes that do not use blessed hashes.
167
168 :repr(autoselect), :repr(default)
169
170 Since version 0.23.
171
172 This representation will select one of the representations above
173 depending on what is best for the situation. Classes not derived from a
174 non-"Object::Pad" base class will pick "native", and classes derived
175 from non-"Object::Pad" bases will pick either the "HASH" or "magic"
176 forms depending on whether the instance is a blessed hash reference or
177 some other kind.
178
179 This achieves the best combination of DWIM while still allowing the
180 common forms of hash reference to be inspected by "Data::Dumper", etc.
181 This is the default representation type, and does not have to be
182 specifically requested.
183
184 role
185 role Name :ATTRS... {
186 ...
187 }
188
189 role Name :ATTRS...;
190
191 Since version 0.32.
192
193 Similar to "class", but provides a package that defines a new role. A
194 role acts simliar to a class in some respects, and differently in
195 others.
196
197 Like a class, a role can have a version, and named methods.
198
199 role Name VERSION {
200 method a { ... }
201 method b { ... }
202 }
203
204 A role does not provide a constructor, and instances cannot directly be
205 constructed. A role cannot extend a class.
206
207 A role can declare that it requires methods of given names from any
208 class that implements the role.
209
210 role Name {
211 requires METHOD;
212 }
213
214 A role can provide instance slots. These are visible to any "BUILD"
215 blocks or methods provided by that role.
216
217 Since version 0.33.
218
219 role Name {
220 has $slot;
221
222 BUILD { $slot = "a value" }
223
224 method slot { return $slot }
225 }
226
227 The following role attributes are supported:
228
229 :compat(invokable)
230
231 Since version 0.35.
232
233 Enables a form of backward-compatibility behaviour useful for gradually
234 upgrading existing code from classical Perl inheritance or mixins into
235 using roles.
236
237 Normally, methods of a role cannot be directly invoked and the role
238 must be applied to an Object::Pad-based class in order to be used. This
239 however presents a problem when gradually upgrading existing code that
240 already uses techniques like roles, multiple inheritance or mixins when
241 that code may be split across multiple distributions, or for some other
242 reason cannot be upgraded all at once. Methods within a role that has
243 the ":compat(invokable)" attribute applied to it may be directly
244 invoked on any object instance. This allows the creation of a role that
245 can still provide code for existing classes written in classical Perl
246 that has not yet been rewritten to use "Object::Pad".
247
248 The tradeoff is that a ":compat(invokable)" role may not create slot
249 data using the "has" keyword. Whatever behaviours the role wishes to
250 perform must be provided only by calling other methods on $self, or
251 perhaps by making assumptions about the representation type of
252 instances.
253
254 It should be stressed again: This option is only intended for gradual
255 upgrade of existing classical Perl code into using "Object::Pad". When
256 all existing code is using "Object::Pad" then this attribute can be
257 removed from the role.
258
259 has
260 has $var;
261 has $var = EXPR;
262 has @var;
263 has %var;
264
265 has $var :ATTR ATTR...;
266
267 Declares that the instances of the class or role have a member field of
268 the given name. This member field (called a "slot") will be accessible
269 as a lexical variable within any "method" declarations in the class.
270
271 Array and hash members are permitted and behave as expected; you do not
272 need to store references to anonymous arrays or hashes.
273
274 Member fields are private to a class or role. They are not visible to
275 users of the class, nor to subclasses, nor to any class that a role is
276 applied to. In order to provide access to them a class may wish to use
277 "method" to create an accessor, or use the attributes such as ":reader"
278 to get one generated.
279
280 A scalar slot may provide a expression that gives an initialisation
281 value, which will be assigned into the slot of every instance during
282 the constructor before the "BUILD" blocks are invoked. Since version
283 0.29 this expression does not have to be a compiletime constant, though
284 it is evaluated exactly once, at runtime, after the class definition
285 has been parsed. It is not evaluated individually for every object
286 instance of that class.
287
288 The following slot attributes are supported:
289
290 :reader, :reader(NAME)
291
292 Since version 0.27.
293
294 Generates a reader method to return the current value of the slot.
295 Currently these are only permitted for scalar slots. If no name is
296 given, the name of the slot is used. A single prefix character "_" will
297 be removed if present.
298
299 has $slot :reader;
300
301 # equivalent to
302 has $slot; method slot { return $slot }
303
304 :writer, :writer(NAME)
305
306 Since version 0.27.
307
308 Generates a writer method to set a new value of the slot from its first
309 argument. Currently these are only permitted for scalar slots. If no
310 name is given, the name of the slot is used prefixed by "set_". A
311 single prefix character "_" will be removed if present.
312
313 has $slot :writer;
314
315 # equivalent to
316 has $slot; method set_slot { $slot = shift; return $self }
317
318 Since version 0.28 a generated writer method will return the object
319 invocant itself, allowing a chaining style.
320
321 $obj->set_x("x")
322 ->set_y("y")
323 ->set_z("z");
324
325 :mutator, :mutator(NAME)
326
327 Since version 0.27.
328
329 Generates an lvalue mutator method to return or set the value of the
330 slot. These are only permitted for scalar slots. If no name is given,
331 the name of the slot is used. A single prefix character "_" will be
332 removed if present.
333
334 has $slot :mutator;
335
336 # equivalent to
337 has $slot; method slot :lvalue { $slot }
338
339 Since version 0.28 all of these generated accessor methods will include
340 argument checking similar to that used by subroutine signatures, to
341 ensure the correct number of arguments are passed - usually zero, but
342 exactly one in the case of a ":writer" method.
343
344 method
345 method NAME {
346 ...
347 }
348
349 method NAME (SIGNATURE) {
350 ...
351 }
352
353 method NAME :ATTRS... {
354 ...
355 }
356
357 Declares a new named method. This behaves similarly to the "sub"
358 keyword, except that within the body of the method all of the member
359 fields ("slots") are also accessible. In addition, the method body will
360 have a lexical called $self which contains the invocant object
361 directly; it will already have been shifted from the @_ array.
362
363 The "signatures" feature is automatically enabled for method
364 declarations. In this case the signature does not have to account for
365 the invocant instance; that is handled directly.
366
367 method m ($one, $two) {
368 say "$self invokes method on one=$one two=$two";
369 }
370
371 ...
372 $obj->m(1, 2);
373
374 A list of attributes may be supplied as for "sub". The most useful of
375 these is ":lvalue", allowing easy creation of read-write accessors for
376 slots (but see also the ":reader", ":writer" and ":mutator" slot
377 attributes).
378
379 class Counter {
380 has $count;
381
382 method count :lvalue { $count }
383 }
384
385 my $c = Counter->new;
386 $c->count++;
387
388 Every method automatically gets the ":method" attribute applied, which
389 suppresses warnings about ambiguous calls resolved to core functions if
390 the name of a method matches a core function.
391
392 The following additional attributes are recognised by "Object::Pad"
393 directly:
394
395 :override
396
397 Since version 0.29.
398
399 Marks that this method expects to override another of the same name
400 from a superclass. It is an error at compiletime if the superclass does
401 not provide such a method.
402
403 BUILD
404 BUILD {
405 ...
406 }
407
408 BUILD (SIGNATURE) {
409 ...
410 }
411
412 Since version 0.27.
413
414 Declares the builder block for this component class. A builder block
415 may use subroutine signature syntax, as for methods, to assist in
416 unpacking its arguments. A build block is not a subroutine and thus is
417 not permitted to use subroutine attributes (for example ":lvalue").
418
419 Currently attempts to create a method named "BUILD" (i.e. with syntax
420 "method BUILD {...}") will create a builder block instead. As of
421 version 0.31 such attempts will print a warning at compiletime, and a
422 later version may remove this altogether.
423
424 requires
425 requires NAME;
426
427 Declares that this role requires a method of the given name from any
428 class that implements it. It is an error at compiletime if the
429 implementing class does not provide such a method.
430
432 In order to encourage users to write clean, modern code, the body of
433 the "class" block acts as if the following pragmata are in effect:
434
435 use strict;
436 use warnings;
437 no indirect ':fatal'; # or no feature 'indirect' on perl 5.32 onwards
438 use feature 'signatures';
439
440 This list may be extended in subsequent versions to add further
441 restrictions and should not be considered exhaustive.
442
443 Further additions will only be ones that remove "discouraged" or
444 deprecated language features with the overall goal of enforcing a more
445 clean modern style within the body. As long as you write code that is
446 in a clean, modern style (and I fully accept that this wording is vague
447 and subjective) you should not find any new restrictions to be majorly
448 problematic. Either the code will continue to run unaffected, or you
449 may have to make some small alterations to bring it into a conforming
450 style.
451
453 There are a number of details specific to the case of deriving an
454 "Object::Pad" class from an existing classic Perl class that is not
455 implemented using "Object::Pad".
456
457 Storage of Instance Data
458 Instances will pick either the ":repr(HASH)" or ":repr(magic)" storage
459 type.
460
461 Object State During Methods Invoked By Superclass Constructor
462 It is common in classic Perl OO style to invoke methods on $self during
463 the constructor. This is supported here since "Object::Pad" version
464 0.19. Note however that any methods invoked by the superclass
465 constructor may not see the object in a fully consistent state. (This
466 fact is not specific to using "Object::Pad" and would happen in classic
467 Perl OO as well). The slot initialisers will have been invoked but the
468 "BUILD" blocks will not.
469
470 For example; in the following
471
472 package ClassicPerlBaseClass {
473 sub new {
474 my $self = bless {}, shift;
475 say "Value seen by superconstructor is ", $self->get_value;
476 return $self;
477 }
478 sub get_value { return "A" }
479 }
480
481 class DerivedClass extends ClassicPerlBaseClass {
482 has $_value = "B";
483 BUILD {
484 $_value = "C";
485 }
486 method get_value { return $_value }
487 }
488
489 my $obj = DerivedClass->new;
490 say "Value seen by user is ", $obj->get_value;
491
492 Until the "ClassicPerlBaseClass::new" superconstructor has returned the
493 "BUILD" block will not have been invoked. The $_value slot will still
494 exist, but its value will be "B" during the superconstructor. After the
495 superconstructor, the "BUILD" blocks are invoked before the completed
496 object is returned to the user. The result will therefore be:
497
498 Value seen by superconstructor is B
499 Value seen by user is C
500
502 While in no way required, the following suggestions of code style
503 should be noted in order to establish a set of best practices, and
504 encourage consistency of code which uses this module.
505
506 $VERSION declaration
507 While it would be nice for CPAN and other toolchain modules to parse
508 the embedded version declarations in "class" statements, the current
509 state at time of writing (June 2020) is that none of them actually do.
510 As such, it will still be necessary to make a once-per-file $VERSION
511 declaration in syntax those modules can parse.
512
513 Further note that these modules will also not parse the "class"
514 declaration, so you will have to duplicate this with a "package"
515 declaration as well as a "class" keyword. This does involve repeating
516 the package name, so is slightly undesirable.
517
518 It is hoped that eventually upstream toolchain modules will be adapted
519 to accept the "class" syntax as being sufficient to declare a package
520 and set its version.
521
522 See also
523
524 • <https://github.com/Perl-Toolchain-Gang/Module-Metadata/issues/33>
525
526 File Layout
527 Begin the file with a "use Object::Pad" line; ideally including a
528 minimum-required version. This should be followed by the toplevel
529 "package" and "class" declarations for the file. As it is at toplevel
530 there is no need to use the block notation; it can be a unit class.
531
532 There is no need to "use strict" or apply other usual pragmata; these
533 will be implied by the "class" keyword.
534
535 use Object::Pad 0.16;
536
537 package My::Classname 1.23;
538 class My::Classname;
539
540 # other use statements
541
542 # has, methods, etc.. can go here
543
544 Slot Names
545 Slot names should follow similar rules to regular lexical variables in
546 code - lowercase, name components separated by underscores. For tiny
547 examples such as "dumb record" structures this may be sufficient.
548
549 class Tag {
550 has $name :mutator;
551 has $value :mutator;
552 }
553
554 In larger examples with lots of non-trivial method bodies, it can get
555 confusing to remember where the slot variables come from (because we no
556 longer have the "$self->{ ... }" visual clue). In these cases it is
557 suggested to prefix the slot names with a leading underscore, to make
558 them more visually distinct.
559
560 class Spudger {
561 has $_grapefruit;
562
563 ...
564
565 method mangle {
566 $_grapefruit->peel; # The leading underscore reminds us this is a slot
567 }
568 }
569
571 Syntax::Keyword::Dynamically
572 A cross-module integration test asserts that "dynamically" works
573 correctly on object instance slots:
574
575 use Object::Pad;
576 use Syntax::Keyword::Dynamically;
577
578 class Container {
579 has $value = 1;
580
581 method example {
582 dynamically $value = 2;
583 ,..
584 # value is restored to 1 on return from this method
585 }
586 }
587
588 Future::AsyncAwait
589 As of Future::AsyncAwait version 0.38 and Object::Pad version 0.15,
590 both modules now use XS::Parse::Sublike to parse blocks of code.
591 Because of this the two modules can operate together and allow class
592 methods to be written as async subs which await expressions:
593
594 use Future::AsyncAwait;
595 use Object::Pad;
596
597 class Example
598 {
599 async method perform ($block)
600 {
601 say "$self is performing code";
602 await $block->();
603 say "code finished";
604 }
605 }
606
607 These three modules combine; there is additionally a cross-module test
608 to ensure that object instance slots can be "dynamically" set during a
609 suspended "async method".
610
612 The following points are details about the design of pad slot-based
613 object systems in general:
614
615 • Is multiple inheritence actually required, if role composition is
616 implemented including giving roles the ability to use private
617 slots?
618
619 • Consider the visibility of superclass slots to subclasses. Do
620 subclasses even need to be able to see their superclass's slots, or
621 are accessor methods always appropriate?
622
623 Concrete example: The "$self->{split_at}" access that
624 Tickit::Widget::HSplit makes of its parent class
625 Tickit::Widget::LinearSplit.
626
628 These points are more about this particular module's implementation:
629
630 • Consider multiple inheritence of subclassing, if that is still
631 considered useful after adding roles.
632
633 • Work out why "no indirect" doesn't appear to work properly before
634 perl 5.20.
635
636 • Work out why we don't get a "Subroutine new redefined at ..."
637 warning if we
638
639 sub new { ... }
640
641 • The "local" modifier does not work on slot variables, because they
642 appear to be regular lexicals to the parser at that point. A
643 workaround is to use Syntax::Keyword::Dynamically instead:
644
645 use Syntax::Keyword::Dynamically;
646
647 has $loglevel;
648
649 method quietly {
650 dynamically $loglevel = LOG_ERROR;
651 ...
652 }
653
655 The following resources are useful forms of providing feedback,
656 especially in the form of reports of what you find good or bad about
657 the module, requests for new features, questions on best practice,
658 etc...
659
660 • The RT queue at
661 <https://rt.cpan.org/Dist/Display.html?Name=Object-Pad>.
662
663 • The "#cor" IRC channel on "irc.perl.org".
664
666 Paul Evans <leonerd@leonerd.org.uk>
667
668
669
670perl v5.32.1 2021-05-14 Object::Pad(3)