1Moose::Manual::AttributUesse(r3)Contributed Perl DocumenMtoaotsieo:n:Manual::Attributes(3)
2
3
4
6 Moose::Manual::Attributes - Object attributes with Moose
7
9 version 2.2015
10
12 Moose attributes have many properties, and attributes are probably the
13 single most powerful and flexible part of Moose. You can create a
14 powerful class simply by declaring attributes. In fact, it's possible
15 to have classes that consist solely of attribute declarations.
16
17 An attribute is a property that every member of a class has. For
18 example, we might say that "every "Person" object has a first name and
19 last name". Attributes can be optional, so that we can say "some
20 "Person" objects have a social security number (and some don't)".
21
22 At its simplest, an attribute can be thought of as a named value (as in
23 a hash) that can be read and set. However, attributes can also have
24 defaults, type constraints, delegation and much more.
25
26 In other languages, attributes are also referred to as slots or
27 properties.
28
30 Use the "has" function to declare an attribute:
31
32 package Person;
33
34 use Moose;
35
36 has 'first_name' => ( is => 'rw' );
37
38 This says that all "Person" objects have an optional read-write
39 "first_name" attribute.
40
41 Read-write vs. read-only
42 The options passed to "has" define the properties of the attribute.
43 There are many options, but in the simplest form you just need to set
44 "is", which can be either "ro" (read-only) or "rw" (read-write). When
45 an attribute is "rw", you can change it by passing a value to its
46 accessor. When an attribute is "ro", you may only read the current
47 value of the attribute through its accessor. You can, however, set the
48 attribute when creating the object by passing it to the constructor.
49
50 In fact, you could even omit "is", but that gives you an attribute that
51 has no accessor. This can be useful with other attribute options, such
52 as "handles". However, if your attribute generates no accessors, Moose
53 will issue a warning, because that usually means the programmer forgot
54 to say the attribute is read-only or read-write. If you really mean to
55 have no accessors, you can silence this warning by setting "is" to
56 "bare".
57
58 Accessor methods
59 Each attribute has one or more accessor methods. An accessor lets you
60 read and write the value of that attribute for an object.
61
62 By default, the accessor method has the same name as the attribute. If
63 you declared your attribute as "ro" then your accessor will be read-
64 only. If you declared it as "rw", you get a read-write accessor.
65 Simple.
66
67 Given our "Person" example above, we now have a single "first_name"
68 accessor that can read or write a "Person" object's "first_name"
69 attribute's value.
70
71 If you want, you can also explicitly specify the method names to be
72 used for reading and writing an attribute's value. This is particularly
73 handy when you'd like an attribute to be publicly readable, but only
74 privately settable. For example:
75
76 has 'weight' => (
77 is => 'ro',
78 writer => '_set_weight',
79 );
80
81 This might be useful if weight is calculated based on other methods.
82 For example, every time the "eat" method is called, we might adjust
83 weight. This lets us hide the implementation details of weight changes,
84 but still provide the weight value to users of the class.
85
86 Some people might prefer to have distinct methods for reading and
87 writing. In Perl Best Practices, Damian Conway recommends that reader
88 methods start with "get_" and writer methods start with "set_".
89
90 We can do exactly that by providing names for both the "reader" and
91 "writer" methods:
92
93 has 'weight' => (
94 is => 'rw',
95 reader => 'get_weight',
96 writer => 'set_weight',
97 );
98
99 If you're thinking that doing this over and over would be insanely
100 tedious, you're right! Fortunately, Moose provides a powerful extension
101 system that lets you override the default naming conventions. See
102 Moose::Manual::MooseX for more details.
103
104 Predicate and clearer methods
105 Moose allows you to explicitly distinguish between a false or undefined
106 attribute value and an attribute which has not been set. If you want to
107 access this information, you must define clearer and predicate methods
108 for an attribute.
109
110 A predicate method tells you whether or not a given attribute is
111 currently set. Note that an attribute can be explicitly set to "undef"
112 or some other false value, but the predicate will return true.
113
114 The clearer method unsets the attribute. This is not the same as
115 setting the value to "undef", but you can only distinguish between them
116 if you define a predicate method!
117
118 Here's some code to illustrate the relationship between an accessor,
119 predicate, and clearer method.
120
121 package Person;
122
123 use Moose;
124
125 has 'ssn' => (
126 is => 'rw',
127 clearer => 'clear_ssn',
128 predicate => 'has_ssn',
129 );
130
131 ...
132
133 my $person = Person->new();
134 $person->has_ssn; # false
135
136 $person->ssn(undef);
137 $person->ssn; # returns undef
138 $person->has_ssn; # true
139
140 $person->clear_ssn;
141 $person->ssn; # returns undef
142 $person->has_ssn; # false
143
144 $person->ssn('123-45-6789');
145 $person->ssn; # returns '123-45-6789'
146 $person->has_ssn; # true
147
148 my $person2 = Person->new( ssn => '111-22-3333');
149 $person2->has_ssn; # true
150
151 By default, Moose does not make a predicate or clearer for you. You
152 must explicitly provide names for them, and then Moose will create the
153 methods for you.
154
155 Required or not?
156 By default, all attributes are optional, and do not need to be provided
157 at object construction time. If you want to make an attribute required,
158 simply set the "required" option to true:
159
160 has 'name' => (
161 is => 'ro',
162 required => 1,
163 );
164
165 There are a couple caveats worth mentioning in regards to what
166 "required" actually means.
167
168 Basically, all it says is that this attribute ("name") must be provided
169 to the constructor or it must have either a default or a builder. It
170 does not say anything about its value, so it could be "undef".
171
172 If you define a clearer method on a required attribute, the clearer
173 will work, so even a required attribute can be unset after object
174 construction.
175
176 This means that if you do make an attribute required, providing a
177 clearer doesn't make much sense. In some cases, it might be handy to
178 have a private "clearer" and "predicate" for a required attribute.
179
180 Default and builder methods
181 Attributes can have default values, and Moose provides two ways to
182 specify that default.
183
184 In the simplest form, you simply provide a non-reference scalar value
185 for the "default" option:
186
187 has 'size' => (
188 is => 'ro',
189 default => 'medium',
190 predicate => 'has_size',
191 );
192
193 If the size attribute is not provided to the constructor, then it ends
194 up being set to "medium":
195
196 my $person = Person->new();
197 $person->size; # medium
198 $person->has_size; # true
199
200 You can also provide a subroutine reference for "default". This
201 reference will be called as a method on the object.
202
203 has 'size' => (
204 is => 'ro',
205 default =>
206 sub { ( 'small', 'medium', 'large' )[ int( rand 3 ) ] },
207 predicate => 'has_size',
208 );
209
210 This is a trivial example, but it illustrates the point that the
211 subroutine will be called for every new object created.
212
213 When you provide a "default" subroutine reference, it is called as a
214 method on the object, with no additional parameters:
215
216 has 'size' => (
217 is => 'ro',
218 default => sub {
219 my $self = shift;
220
221 return $self->height > 200 ? 'large' : 'average';
222 },
223 );
224
225 When the "default" is called during object construction, it may be
226 called before other attributes have been set. If your default is
227 dependent on other parts of the object's state, you can make the
228 attribute "lazy". Laziness is covered in the next section.
229
230 If you want to use a reference of any sort as the default value, you
231 must return it from a subroutine.
232
233 has 'mapping' => (
234 is => 'ro',
235 default => sub { {} },
236 );
237
238 This is necessary because otherwise Perl would instantiate the
239 reference exactly once, and it would be shared by all objects:
240
241 has 'mapping' => (
242 is => 'ro',
243 default => {}, # wrong!
244 );
245
246 Moose will throw an error if you pass a bare non-subroutine reference
247 as the default.
248
249 If Moose allowed this then the default mapping attribute could easily
250 end up shared across many objects. Instead, wrap it in a subroutine
251 reference as we saw above.
252
253 This is a bit awkward, but it's just the way Perl works.
254
255 As an alternative to using a subroutine reference, you can supply a
256 "builder" method for your attribute:
257
258 has 'size' => (
259 is => 'ro',
260 builder => '_build_size',
261 predicate => 'has_size',
262 );
263
264 sub _build_size {
265 return ( 'small', 'medium', 'large' )[ int( rand 3 ) ];
266 }
267
268 This has several advantages. First, it moves a chunk of code to its own
269 named method, which improves readability and code organization. Second,
270 because this is a named method, it can be subclassed or provided by a
271 role.
272
273 We strongly recommend that you use a "builder" instead of a "default"
274 for anything beyond the most trivial default.
275
276 A "builder", just like a "default", is called as a method on the object
277 with no additional parameters.
278
279 Builders allow subclassing
280
281 Because the "builder" is called by name, it goes through Perl's method
282 resolution. This means that builder methods are both inheritable and
283 overridable.
284
285 If we subclass our "Person" class, we can override "_build_size":
286
287 package Lilliputian;
288
289 use Moose;
290 extends 'Person';
291
292 sub _build_size { return 'small' }
293
294 Builders work well with roles
295
296 Because builders are called by name, they work well with roles. For
297 example, a role could provide an attribute but require that the
298 consuming class provide the "builder":
299
300 package HasSize;
301 use Moose::Role;
302
303 requires '_build_size';
304
305 has 'size' => (
306 is => 'ro',
307 lazy => 1,
308 builder => '_build_size',
309 );
310
311 package Lilliputian;
312 use Moose;
313
314 with 'HasSize';
315
316 sub _build_size { return 'small' }
317
318 Roles are covered in Moose::Manual::Roles.
319
320 Laziness
321 Moose lets you defer attribute population by making an attribute
322 "lazy":
323
324 has 'size' => (
325 is => 'ro',
326 lazy => 1,
327 builder => '_build_size',
328 );
329
330 When "lazy" is true, the default is not generated until the reader
331 method is called, rather than at object construction time. There are
332 several reasons you might choose to do this.
333
334 First, if the default value for this attribute depends on some other
335 attributes, then the attribute must be "lazy". During object
336 construction, defaults are not generated in a predictable order, so you
337 cannot count on some other attribute being populated when generating a
338 default.
339
340 Second, there's often no reason to calculate a default before it's
341 needed. Making an attribute "lazy" lets you defer the cost until the
342 attribute is needed. If the attribute is never needed, you save some
343 CPU time.
344
345 We recommend that you make any attribute with a builder or non-trivial
346 default "lazy" as a matter of course.
347
348 Lazy defaults and $_
349
350 Please note that a lazy default or builder can be called anywhere, even
351 inside a "map" or "grep". This means that if your default sub or
352 builder changes $_, something weird could happen. You can prevent this
353 by adding "local $_" inside your default or builder.
354
355 Constructor parameters ("init_arg")
356 By default, each attribute can be passed by name to the class's
357 constructor. On occasion, you may want to use a different name for the
358 constructor parameter. You may also want to make an attribute
359 unsettable via the constructor.
360
361 You can do either of these things with the "init_arg" option:
362
363 has 'bigness' => (
364 is => 'ro',
365 init_arg => 'size',
366 );
367
368 Now we have an attribute named "bigness", but we pass "size" to the
369 constructor.
370
371 Even more useful is the ability to disable setting an attribute via the
372 constructor. This is particularly handy for private attributes:
373
374 has '_genetic_code' => (
375 is => 'ro',
376 lazy => 1,
377 builder => '_build_genetic_code',
378 init_arg => undef,
379 );
380
381 By setting the "init_arg" to "undef", we make it impossible to set this
382 attribute when creating a new object.
383
384 Weak references
385 Moose has built-in support for weak references. If you set the
386 "weak_ref" option to a true value, then it will call
387 "Scalar::Util::weaken" whenever the attribute is set:
388
389 has 'parent' => (
390 is => 'rw',
391 weak_ref => 1,
392 );
393
394 $node->parent($parent_node);
395
396 This is very useful when you're building objects that may contain
397 circular references.
398
399 When the object in a weak reference goes out of scope, the attribute's
400 value will become "undef" "behind the scenes". This is done by the Perl
401 interpreter directly, so Moose does not see this change. This means
402 that triggers don't fire, coercions aren't applied, etc.
403
404 The attribute is not cleared, so a predicate method for that attribute
405 will still return true. Similarly, when the attribute is next accessed,
406 a default value will not be generated.
407
408 Triggers
409 A "trigger" is a subroutine that is called whenever the attribute is
410 set:
411
412 has 'size' => (
413 is => 'rw',
414 trigger => \&_size_set,
415 );
416
417 sub _size_set {
418 my ( $self, $size, $old_size ) = @_;
419
420 my $msg = $self->name;
421
422 if ( @_ > 2 ) {
423 $msg .= " - old size was $old_size";
424 }
425
426 $msg .= " - size is now $size";
427 warn $msg;
428 }
429
430 The trigger is called after an attribute's value is set. It is called
431 as a method on the object, and receives the new and old values as its
432 arguments. If the attribute had not previously been set at all, then
433 only the new value is passed. This lets you distinguish between the
434 case where the attribute had no value versus when the old value was
435 "undef".
436
437 This differs from an "after" method modifier in two ways. First, a
438 trigger is only called when the attribute is set, as opposed to
439 whenever the accessor method is called (for reading or writing).
440 Second, it is also called when an attribute's value is passed to the
441 constructor.
442
443 However, triggers are not called when an attribute is populated from a
444 "default" or "builder".
445
446 Attribute types
447 Attributes can be restricted to only accept certain types:
448
449 has 'first_name' => (
450 is => 'ro',
451 isa => 'Str',
452 );
453
454 This says that the "first_name" attribute must be a string.
455
456 Moose also provides a shortcut for specifying that an attribute only
457 accepts objects that do a certain role:
458
459 has 'weapon' => (
460 is => 'rw',
461 does => 'MyApp::Weapon',
462 );
463
464 See the Moose::Manual::Types documentation for a complete discussion of
465 Moose's type system.
466
467 Delegation
468 An attribute can define methods which simply delegate to its value:
469
470 has 'hair_color' => (
471 is => 'ro',
472 isa => 'Graphics::Color::RGB',
473 handles => { hair_color_hex => 'as_hex_string' },
474 );
475
476 This adds a new method, "hair_color_hex". When someone calls
477 "hair_color_hex", internally, the object just calls
478 "$self->hair_color->as_hex_string".
479
480 See Moose::Manual::Delegation for documentation on how to set up
481 delegation methods.
482
483 Attribute traits and metaclasses
484 One of Moose's best features is that it can be extended in all sorts of
485 ways through the use of metaclass traits and custom metaclasses.
486
487 You can apply one or more traits to an attribute:
488
489 use MooseX::MetaDescription;
490
491 has 'size' => (
492 is => 'ro',
493 traits => ['MooseX::MetaDescription::Meta::Trait'],
494 description => {
495 html_widget => 'text_input',
496 serialize_as => 'element',
497 },
498 );
499
500 The advantage of traits is that you can mix more than one of them
501 together easily (in fact, a trait is just a role under the hood).
502
503 There are a number of MooseX modules on CPAN which provide useful
504 attribute metaclasses and traits. See Moose::Manual::MooseX for some
505 examples. You can also write your own metaclasses and traits. See the
506 "Meta" and "Extending" recipes in Moose::Cookbook for examples.
507
508 Native Delegations
509 Native delegations allow you to delegate to standard Perl data
510 structures as if they were objects.
511
512 For example, we can pretend that an array reference has methods like
513 "push()", "shift()", "map()", "count()", and more.
514
515 has 'options' => (
516 traits => ['Array'],
517 is => 'ro',
518 isa => 'ArrayRef[Str]',
519 default => sub { [] },
520 handles => {
521 all_options => 'elements',
522 add_option => 'push',
523 map_options => 'map',
524 option_count => 'count',
525 sorted_options => 'sort',
526 },
527 );
528
529 See Moose::Manual::Delegation for more details.
530
532 By default, a child inherits all of its parent class(es)' attributes
533 as-is. However, you can change most aspects of the inherited attribute
534 in the child class. You cannot change any of its associated method
535 names (reader, writer, predicate, etc).
536
537 To change some aspects of an attribute, you simply prepend a plus sign
538 ("+") to its name:
539
540 package LazyPerson;
541
542 use Moose;
543
544 extends 'Person';
545
546 has '+first_name' => (
547 lazy => 1,
548 default => 'Bill',
549 );
550
551 Now the "first_name" attribute in "LazyPerson" is lazy, and defaults to
552 'Bill'.
553
554 We recommend that you exercise caution when changing the type ("isa")
555 of an inherited attribute.
556
557 Attribute Inheritance and Method Modifiers
558 When an inherited attribute is defined, that creates an entirely new
559 set of accessors for the attribute (reader, writer, predicate, etc.).
560 This is necessary because these may be what was changed when inheriting
561 the attribute.
562
563 As a consequence, any method modifiers defined on the attribute's
564 accessors in an ancestor class will effectively be ignored, because the
565 new accessors live in the child class and do not see the modifiers from
566 the parent class.
567
569 If you have a number of attributes that differ only by name, you can
570 declare them all at once:
571
572 package Point;
573
574 use Moose;
575
576 has [ 'x', 'y' ] => ( is => 'ro', isa => 'Int' );
577
578 Also, because "has" is just a function call, you can call it in a loop:
579
580 for my $name ( qw( x y ) ) {
581 my $builder = '_build_' . $name;
582 has $name => ( is => 'ro', isa => 'Int', builder => $builder );
583 }
584
586 Moose attributes are a big topic, and this document glosses over a few
587 aspects. We recommend that you read the Moose::Manual::Delegation and
588 Moose::Manual::Types documents to get a more complete understanding of
589 attribute features.
590
592 Moose has lots of attribute options. The ones listed below are
593 superseded by some more modern features, but are covered for the sake
594 of completeness.
595
596 The "documentation" option
597 You can provide a piece of documentation as a string for an attribute:
598
599 has 'first_name' => (
600 is => 'rw',
601 documentation => q{The person's first (personal) name},
602 );
603
604 Moose does absolutely nothing with this information other than store
605 it.
606
607 The "auto_deref" option
608 If your attribute is an array reference or hash reference, the
609 "auto_deref" option will make Moose dereference the value when it is
610 returned from the reader method in list context:
611
612 my %map = $object->mapping;
613
614 This option only works if your attribute is explicitly typed as an
615 "ArrayRef" or "HashRef". When the reader is called in scalar context,
616 the reference itself is returned.
617
618 However, we recommend that you use Moose::Meta::Attribute::Native
619 traits for these types of attributes, which gives you much more control
620 over how they are accessed and manipulated. See also
621 Moose::Manual::BestPractices#Use_Moose::Meta::Attribute::Native_traits_instead_of_auto_deref.
622
623 Initializer
624 Moose provides an attribute option called "initializer". This is called
625 when the attribute's value is being set in the constructor, and lets
626 you change the value before it is set.
627
629 • Stevan Little <stevan@cpan.org>
630
631 • Dave Rolsky <autarch@urth.org>
632
633 • Jesse Luehrs <doy@cpan.org>
634
635 • Shawn M Moore <sartak@cpan.org>
636
637 • יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
638
639 • Karen Etheridge <ether@cpan.org>
640
641 • Florian Ragwitz <rafl@debian.org>
642
643 • Hans Dieter Pearcey <hdp@cpan.org>
644
645 • Chris Prather <chris@prather.org>
646
647 • Matt S Trout <mstrout@cpan.org>
648
650 This software is copyright (c) 2006 by Infinity Interactive, Inc.
651
652 This is free software; you can redistribute it and/or modify it under
653 the same terms as the Perl 5 programming language system itself.
654
655
656
657perl v5.34.0 2021-07-22 Moose::Manual::Attributes(3)