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