5 Moose::Manual::Attribute - Object attributes with Moose
9 Attributes are the most feature-rich part of Moose, and also one of
10 the most useful. It's easy to imagine a class without roles or method
11 modifiers, but almost every class has attributes.
13 Attributes are properties that every member of a class has. For
14 example, we might say that "every Person object has a first name and
15 last name. Attributes can be optional, so that we can say "some Person
16 objects have a social security number (and some don't)".
18 At its simplest, an attribute can be thought of slot in hash that can
19 be read and set. However, attributes, can also have things like
20 default values, laziness, type constraints, delegation and much more.
22 =head1 ATTRIBUTE OPTIONS
24 Use the C<has> function to declare an attribute:
30 has 'first_name' => ( is => 'rw' );
32 This says that all person objects have an optional "first_name"
33 attribute that can be both read and set on the object.
35 =head2 Read-write Vs Read-only
37 The code inside the parentheses defines the details of the
38 attribute. There are a lot of options you can put here, but in the
39 simplest form you just need to include C<is>, which can be either
40 C<rw> (read-write) or C<ro> (read-only).
42 (In fact, you could even omit C<is>, but that leaves you with an
43 attribute that has no accessors, which is pointless unless you're
44 doing some deep, dark magic).
46 =head2 Accessor Methods
48 Each attribute has one or more accessor methods. An accessor lets you
49 read and write the value of the attribute for an object.
51 By default, the accessor method has the same name as the attribute. If
52 you declared your attribute as C<ro> then your accessor will be
53 read-only. If you declared it read-write, you get a read-write
56 So with our Person example above, we now have a single C<first_name>
57 accessor that can set or return a person object's first name.
59 If you want, you can also explicitly specify the method names to be
60 used for reading and writing an attribute's value. This is
61 particularly handy when you'd like an attribute to be publically
62 readable, but only privately settable. For example:
66 writer => '_set_weight',
69 This might be useful if weight is calculated based on other methods,
70 for example every time the C<eat> method is called, we might adjust
71 weight. This lets us hide the implementation details of weight
72 changes, but still provide the weight value to users of the class.
74 Some people might prefer to have distinct methods for reading and
75 writing, even when writing is a public method. In I<Perl Best
76 Practices>, Damian Conway recommends that reader methods start with
77 "get_" and writer methods start with "set_".
79 We can do exactly that by providing names for both the C<reader> and
84 reader => 'get_weight',
85 writer => 'set_weight',
88 If you're thinking that doing this over and over would be insanely
89 tedious, you're right! Fortunately, Moose provides a powerful
90 extension system that lets you do things like override the default
91 accessor method conventions. See L<Moose::Manual::MooseX> for more
94 =head2 Predicate and Clearer Methods
96 Moose is able to explicitly distinguish between false or undefined
97 values, and an attribute which is not set. If you want to be able to
98 access and manipulate these states, you also need to define clearer
99 and predicate methods for your attributes.
101 A predicate method can be used to determine whether or not a given
102 attribute is currently set. Note that even if the attribute was
103 explicitly set to undef or some other false value, the predicate will
106 The clearer method unsets the attribute. This is I<not> the
107 same as setting the value to C<undef>, but you can only distinguish
108 between them if you define a predicate method!
110 Here's some code to illustrate the relationship between an accessor,
111 predicate, and clearer method.
119 clearer => 'clear_ssn',
120 predicate => 'has_ssn',
125 my $person = Person->new();
126 $person->has_ssn; # false
129 $person->ssn; # returns undef
130 $person->has_ssn; # true
133 $person->ssn; # returns undef
134 $person->has_ssn; # false
136 $person->ssn('123-45-6789');
137 $person->ssn; # returns '123-45-6789'
138 $person->has_ssn; # true
140 my $person2 = Person->new( ssn => '111-22-3333');
141 $person2->has_ssn; # true
143 Note that by default, Moose does not make a predicate or clearer for
144 you. You have to explicitly provide a method name for the ones you
147 =head2 Required or Not?
149 By default, all attributes are optional. That means that they do not
150 need to be provided at object construction time. If you want to make
151 an attribute 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 must be provided to the
162 constructor. It does not say anything about its value, so it could be
165 If you define a clearer method on a required attribute, the clearer
166 I<will> work. So even though something is defined as required, you can
167 remove it after object construction.
169 So if you do make an attribute required, that probably means that
170 providing a clearer doesn't make much sense. In some cases, it might
171 be handy to have a I<private> C<clearer> and C<predicate> for a
174 =head2 Default and Builder Methods
176 Attributes can have default values, and there are several ways to
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 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 before
209 other attributes have been set. If your default is dependent on other
210 parts of the object's state, you can make the default c<lazy>, which
211 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 If Moose allowed this then the default mapping attribute could easily
224 end up shared across many objects. Instead, wrap it in a subroutine
229 default => sub { {} }, # right!
232 This is a bit awkward, but it's just the way Perl works.
234 As an alternative to using a subroutine reference, you can instead
235 supply a C<builder> method for your attribute:
239 builder => '_build_size',
240 predicate => 'has_size',
244 return ('small', 'medium', 'large')[ int( rand 3 ) ];
247 This has several advantages. First, it moves a chunk of code to its
248 own named method, which improves readability and code
249 organization. Second, the C<_build_size> method can be overridden in
252 We strongly recommend that you use a C<builder> instead of a
253 C<default> for anything beyond the most trivial default.
255 =head2 Laziness and lazy_build
257 Moose lets you defer attribute population by making an attribute
263 builder => '_build_size',
266 When the C<lazy> option is true, the attribute is not populated until
267 the reader method is called, rather than at object construction
268 time. There are several reasons you might choose to do this.
270 First, if the default value for this attribute depends on some other
271 attributes, then the attribute I<must> be C<lazy>. During object
272 construction, default subroutine references are not called in any
273 particular order, so you cannot count on other attribute being
274 populated at that time.
276 Second, there's often no reason to spend program time calculating a
277 default before its needed. Making an attribute C<lazy> lets you defer
278 the cost until the attribute is needed. If the attribute is I<never>
279 needed, you save some CPU time.
281 We recommend that you make any attribute with a builder or non-trivial
282 default C<lazy> as a matter of course.
284 To facilitate this, you can simply specify the C<lazy_build> attribute
285 option. This bundles up a number of options together:
292 This is the same as specifying all of these options:
297 builder => '_build_size',
298 clearer => 'clear_size',
299 predicate => 'has_size',
302 If your attribute name starts with an underscore (_), then the clearer
303 and predicate will as well:
315 builder => '_build__size',
316 clearer => '_clear_size',
317 predicate => '_has_size',
320 Note the doubled underscore in the builder name. Internally, Moose
321 simply prepends the attribute name with "_build_" to come up with the
324 If you don't like the names that C<lazy_build> generates, you can
325 always provide your own:
330 clearer => '_has_size',
333 Options that you explicitly provide are always used in favor of
334 Moose's internal defaults.
336 =head2 Weak References
338 Moose has built-in support for weak references. If you set the
339 C<weak_ref> to a true value for the attribute, then it will call
340 C<Scalar::Util::weaken> whenever the attribute is set:
347 $node->parent($parent_node);
349 This is very useful when you're building objects that may contain
354 You can provide a C<trigger> option as a subroutine reference which
355 will be called whenever the attribute is set:
359 trigger => \&_size_set,
363 my ( $self, $size, $meta_attr ) = @_;
365 print $self->name, " size is now $size\n";
368 The trigger is called as a method, and receives the new value as well
369 as the L<Moose::Meta::Attribute> object for the attribute.
371 =head2 Attribute Types
373 Attributes can be restriced to only accept certain types:
380 This says that the first_name attribute must be a string.
382 Moose also provides a shortcut for specifying that an attribute only
383 accepts objects that do a certain role:
387 does => 'MyApp::Weapon',
390 See the L<Moose::Manual::Types> documentation for a complete
391 discussion of Moose's type system.
395 Attributes can define delegations to their values:
399 isa => 'Graphics::Color::RGB',
400 handles => { hair_color_hex => 'as_hex_string' },
403 This adds a new method, C<hair_color_hex>. Internally, this just calls
404 C<< $self->hair_color->as_hex_string >>.
406 See L<Moose::Manual::Delegation> for more details on how to set up
409 =head2 Metaclass and traits
411 One of Moose's best features is that it can be extended in all sorts
412 of ways through the use of new metaclasses and metaclass traits.
414 When declaring an attribute, you can declare a metaclass or a set of
415 traits for the attribute:
417 use MooseX::AttributeHelpers;
420 ( metaclass => 'Collection::Hash',
422 default => sub { {} },
425 In this case, the metaclass C<Collection::Hash> really refers to
426 C<MooseX::AttributeHelpers::Collection::Hash>.
428 You can also apply one or more traits to an attribute:
431 use MooseX::MetaDescription;
435 traits => [ 'MooseX::MetaDescription::Meta::Trait' ],
436 description => { html_widget => 'text_input',
437 serialize_as => 'element',
441 The advantage of traits is that you can mix more than one of them
442 together easily (in fact, a trait is just a role under the hood).
444 There are a number of MooseX modules on CPAN which provide useful
445 attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
446 some examples. You can also write your own metaclasses and traits. See
447 the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
449 =head2 Attribute Inheritance
451 By default, a child inherits all of its parent class(es)' attributes
452 as-is. You can explicitly change some aspects of the inherited
453 attribute in the child class.
455 The options that can be overridden in a subclass are:
465 =item * documentation
481 To override an attribute, you simply prepend its name with a plus sign
495 Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
498 We recommend that you exercise caution when changing the type (C<isa>)
499 of an inherited attribute. It's best to only make the new type a
500 subtype of the one accepted by the parent.
502 =head2 The C<documentation> option
504 You can provide a piece of documentation as a string for an attribute:
508 documentation => q{The person's first (personal) name},
511 Moose does absolutely nothing with this information other than store
514 As an alternative, you might want to look at the
515 C<MooseX::MetaDescription> module, which lets you attach a
516 "description" to each attribute. This description is a hashref that
517 can include meta-information intended for use in other code, as well
518 as documentation information.
520 =head2 The C<auto_deref> Option
522 If your attribute is an array reference or hash reference, the
523 C<auto_deref> option will make Moose de-reference the value when it is
524 returned from the reader method:
526 my %map = $object->mapping;
528 This option only works if your attribute is explicitly typed as an
531 However, we recommend that you use C<MooseX::AttributeHelpers> for
532 these types of attributes, which gives you much more control over how
533 they are accessed and manipulated.
537 Moose provides an attribute option called C<initializer>. This is
538 similar to C<builder>, except that it is I<only> called during object
541 This option is inherited from C<Class::MOP>, but we recommend that you
542 use a C<builder> (which is Moose-only) instead.
544 =head1 MORE ON ATTRIBUTES
546 Moose attributes are a big topic, and this document glosses over a few
547 topics. We recommend that you read the L<Moose::Manual::Delegation>
548 and L<Moose::Manual::Types> documents to get a more complete
549 understanding of attribute features.