5 Moose::Manual::Attribute - Object attributes with Moose
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.
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 Person
17 objects have a social security number (and some don't)".
19 At its simplest, an attribute can be thought of as a named value (as
20 in a hash) that can be read and set. However, attributes can also have
21 defaults, type constraints, delegation and much more.
23 In other languages, attributes are also referred to as slots or
26 =head1 ATTRIBUTE OPTIONS
28 Use the C<has> function to declare an attribute:
34 has 'first_name' => ( is => 'rw' );
36 This says that all person objects have an optional read-write
37 "first_name" attribute.
39 =head2 Read-write Vs Read-only
41 The options passed to C<has> define the properties of the
42 attribute. There are a many options, but in the simplest form you just
43 need to set C<is>, which can be either C<rw> (read-write) or C<ro>
46 (In fact, you could even omit C<is>, but that gives you an attribute
47 that has no accessors, which is pointless unless you're doing some
50 =head2 Accessor Methods
52 Each attribute has one or more accessor methods. An accessor lets you
53 read and write the value of that attribute for an object.
55 By default, the accessor method has the same name as the attribute. If
56 you declared your attribute as C<ro> then your accessor will be
57 read-only. If you declared it read-write, you get a read-write
60 Given our Person example above, we now have a single C<first_name>
61 accessor that can read or write a person object's first name.
63 If you want, you can also explicitly specify the method names to be
64 used for reading and writing an attribute's value. This is
65 particularly handy when you'd like an attribute to be publically
66 readable, but only privately settable. For example:
70 writer => '_set_weight',
73 This might be useful if weight is calculated based on other methods,
74 for example every time the C<eat> method is called, we might adjust
75 weight. This lets us hide the implementation details of weight
76 changes, but still provide the weight value to users of the class.
78 Some people might prefer to have distinct methods for reading and
79 writing. In I<Perl Best Practices>, Damian Conway recommends that
80 reader methods start with "get_" and writer methods start with "set_".
82 We can do exactly that by providing names for both the C<reader> and
87 reader => 'get_weight',
88 writer => 'set_weight',
91 If you're thinking that doing this over and over would be insanely
92 tedious, you're right! Fortunately, Moose provides a powerful
93 extension system that lets override the default naming
94 conventions. See L<Moose::Manual::MooseX> for more details.
96 =head2 Predicate and Clearer Methods
98 Moose allows you to explicitly distinguish between a false or
99 undefined attribute value and an attribute which has not been set. If
100 you want to access this information, you must define clearer and
101 predicate methods for an attribute.
103 A predicate method tells you whether or not a given attribute is
104 currently set. Note an attribute can be explicitly set to undef or
105 some other false value, but the predicate will return true.
107 The clearer method unsets the attribute. This is I<not> the
108 same as setting the value to C<undef>, but you can only distinguish
109 between them if you define a predicate method!
111 Here's some code to illustrate the relationship between an accessor,
112 predicate, and clearer method.
120 clearer => 'clear_ssn',
121 predicate => 'has_ssn',
126 my $person = Person->new();
127 $person->has_ssn; # false
130 $person->ssn; # returns undef
131 $person->has_ssn; # true
134 $person->ssn; # returns undef
135 $person->has_ssn; # false
137 $person->ssn('123-45-6789');
138 $person->ssn; # returns '123-45-6789'
139 $person->has_ssn; # true
141 my $person2 = Person->new( ssn => '111-22-3333');
142 $person2->has_ssn; # true
144 By default, Moose does not make a predicate or clearer for you. You
145 must explicitly provide names for them.
147 =head2 Required or Not?
149 By default, all attributes are optional, and do not need to be
150 provided at object construction time. If you want to make an attribute
151 required, simply set the C<required> option to true:
158 There are a couple caveats worth mentioning in regards to what
159 required actually means.
161 Basically, all it says is that this attribute (name) must be provided
162 to the constructor. It does not say anything about its value, so it
165 If you define a clearer method on a required attribute, the clearer
166 I<will> work, so even a required attribute can be unset after object
169 This means that if you do make an attribute required, providing a
170 clearer doesn't make much sense. In some cases, it might be handy to
171 have a I<private> C<clearer> and C<predicate> for a required
174 =head2 Default and Builder Methods
176 Attributes can have default values, and Moose provides two ways to
177 specify that default.
179 In the simplest form, you simply provide a non-reference scalar value
180 for the C<default> option:
185 predicate => 'has_size',
188 If the size attribute is not provided to the constructor, then it ends
189 up being set to "medium":
191 my $person = Person->new();
192 $person->size; # medium
193 $person->has_size; # true
195 You can also provide a subroutine reference for C<default>. This
196 reference will be called as a method on the object.
201 sub { ( 'small', 'medium', 'large' )[ int( rand 3 ) ] },
202 predicate => 'has_size',
205 This is dumb example, but it illustrates the point that the subroutine
206 will be called for every new object created.
208 Of course, if it's called during object construction, it may be called
209 before other attributes have been set. If your default is dependent on
210 other parts of the object's state, you can make the attribute
211 C<lazy>. Laziness is covered in the next section.
213 If you want to use a reference of any sort as the default value, you
214 must return it from a subroutine. This is necessary because otherwise
215 Perl would instantiate the reference exactly once, and it would be
216 shared by all objects:
220 default => {}, # wrong!
223 Moose will throw an error if you pass a bare non-subroutine reference
226 If Moose allowed this then the default mapping attribute could easily
227 end up shared across many objects. Instead, wrap it in a subroutine
232 default => sub { {} }, # right!
235 This is a bit awkward, but it's just the way Perl works.
237 As an alternative to using a subroutine reference, you can instead
238 supply a C<builder> method for your attribute:
242 builder => '_build_size',
243 predicate => 'has_size',
247 return ( 'small', 'medium', 'large' )[ int( rand 3 ) ];
250 This has several advantages. First, it moves a chunk of code to its
251 own named method, which improves readability and code
252 organization. Second, the C<_build_size> method can be overridden in
255 We strongly recommend that you use a C<builder> instead of a
256 C<default> for anything beyond the most trivial default.
258 =head2 Laziness and lazy_build
260 Moose lets you defer attribute population by making an attribute
266 builder => '_build_size',
269 When C<lazy> is true, the default is not generated until the reader
270 method is called, rather than at object construction time. There are
271 several reasons you might choose to do this.
273 First, if the default value for this attribute depends on some other
274 attributes, then the attribute I<must> be C<lazy>. During object
275 construction, defaults are not generated in a predictable order, so
276 you cannot count on some other attribute being populated when
277 generating a default.
279 Second, there's often no reason to calculate a default before it's
280 needed. Making an attribute C<lazy> lets you defer the cost until the
281 attribute is needed. If the attribute is I<never> needed, you save
284 We recommend that you make any attribute with a builder or non-trivial
285 default C<lazy> as a matter of course.
287 To facilitate this, you can simply specify the C<lazy_build> attribute
288 option. This bundles up a number of options together:
295 This is the same as specifying all of these options:
300 builder => '_build_size',
301 clearer => 'clear_size',
302 predicate => 'has_size',
305 If your attribute name starts with an underscore (_), then the clearer
306 and predicate will as well:
318 builder => '_build__size',
319 clearer => '_clear_size',
320 predicate => '_has_size',
323 Note the doubled underscore in the builder name. Internally, Moose
324 simply prepends the attribute name with "_build_" to come up with the
327 If you don't like the names that C<lazy_build> generates, you can
328 always provide your own:
333 clearer => '_clear_size',
336 Options that you explicitly provide are always used in favor of
337 Moose's internal defaults.
339 =head2 Constructor Parameters (init_arg)
341 By default, each attribute can be passed by name to the class's
342 constructor. On occassion, you may want to use a different name for
343 the constructor parameter. You may also want to make an attribute
344 unsettable via the constructor.
346 Both of these goals can be accomplished with the C<init_arg> option:
353 Now we have an attribute named bigness, but we pass C<size> to the
356 Even more useful is the ability to disable setting an attribute via
357 the constructor. This is particularly handy for private attributes:
359 has '_genetic_code' => (
365 By setting the C<init_arg> to C<undef>, we make it impossible to set
366 this attribute when creating a new object.
368 =head2 Weak References
370 Moose has built-in support for weak references. If you set the
371 C<weak_ref> option to a true value, then it will call
372 C<Scalar::Util::weaken> whenever the attribute is set:
379 $node->parent($parent_node);
381 This is very useful when you're building objects that may contain
386 A C<trigger> is a subroutine that is called whenever the attribute is
391 trigger => \&_size_set,
395 my ( $self, $size, $meta_attr ) = @_;
397 warn $self->name, " size is now $size\n";
400 The trigger is called as a method, and receives the new value as well
401 as the L<Moose::Meta::Attribute> object for the attribute. The trigger
402 is called I<after> the value is set.
404 =head2 Attribute Types
406 Attributes can be restricted to only accept certain types:
408 has 'first_name' => (
413 This says that the first_name attribute must be a string.
415 Moose also provides a shortcut for specifying that an attribute only
416 accepts objects that do a certain role:
420 does => 'MyApp::Weapon',
423 See the L<Moose::Manual::Types> documentation for a complete
424 discussion of Moose's type system.
428 Attributes can define methods which simple delegate to their values:
430 has 'hair_color' => (
432 isa => 'Graphics::Color::RGB',
433 handles => { hair_color_hex => 'as_hex_string' },
436 This adds a new method, C<hair_color_hex>. When someone calls
437 C<hair_color_hex>, internally, the object just calls C<<
438 $self->hair_color->as_hex_string >>.
440 See L<Moose::Manual::Delegation> for documentation on how to set up
443 =head2 Metaclass and traits
445 One of Moose's best features is that it can be extended in all sorts
446 of ways through the use of custom metaclasses and metaclass traits.
448 When declaring an attribute, you can declare a metaclass or a set of
449 traits for the attribute:
451 use MooseX::AttributeHelpers;
454 metaclass => 'Collection::Hash',
456 default => sub { {} },
459 In this case, the metaclass C<Collection::Hash> really refers to
460 C<MooseX::AttributeHelpers::Collection::Hash>.
462 You can also apply one or more traits to an attribute:
464 use MooseX::MetaDescription;
468 traits => ['MooseX::MetaDescription::Meta::Trait'],
470 html_widget => 'text_input',
471 serialize_as => 'element',
475 The advantage of traits is that you can mix more than one of them
476 together easily (in fact, a trait is just a role under the hood).
478 There are a number of MooseX modules on CPAN which provide useful
479 attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
480 some examples. You can also write your own metaclasses and traits. See
481 the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
483 =head1 ATTRIBUTE INHERITANCE
485 By default, a child inherits all of its parent class(es)' attributes
486 as-is. However, you can explicitly change some aspects of the
487 inherited attribute in the child class.
489 The options that can be overridden in a subclass are:
499 =item * documentation
515 To override an attribute, you simply prepend its name with a plus sign
524 has '+first_name' => (
529 Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
532 We recommend that you exercise caution when changing the type (C<isa>)
533 of an inherited attribute.
535 =head1 MORE ON ATTRIBUTES
537 Moose attributes are a big topic, and this document glosses over a few
538 aspects of their aspects. We recommend that you read the
539 L<Moose::Manual::Delegation> and L<Moose::Manual::Types> documents to
540 get a more complete understanding of attribute features.
542 =head1 A FEW MORE OPTIONS
544 Moose has lots of attribute options. The ones listed below are
545 superceded by some more modern features, but are covered for the sake
548 =head2 The C<documentation> option
550 You can provide a piece of documentation as a string for an attribute:
552 has 'first_name' => (
554 documentation => q{The person's first (personal) name},
557 Moose does absolutely nothing with this information other than store
560 =head2 The C<auto_deref> Option
562 If your attribute is an array reference or hash reference, the
563 C<auto_deref> option will make Moose de-reference the value when it is
564 returned from the reader method:
566 my %map = $object->mapping;
568 This option only works if your attribute is explicitly typed as an
571 However, we recommend that you use C<MooseX::AttributeHelpers> for
572 these types of attributes, which gives you much more control over how
573 they are accessed and manipulated.
577 Moose provides an attribute option called C<initializer>. This is
578 similar to C<builder>, except that it is I<only> called during object
581 This option is inherited from C<Class::MOP>, but we recommend that you
582 use a C<builder> (which is Moose-only) instead.
586 Dave Rolsky E<lt>autarch@urth.orgE<gt>
588 =head1 COPYRIGHT AND LICENSE
590 Copyright 2009 by Infinity Interactive, Inc.
592 L<http://www.iinteractive.com>
594 This library is free software; you can redistribute it and/or modify
595 it under the same terms as Perl itself.