5 Moose::Manual::Attribute - Object attributes with Moose
9 Moose has many attribute-related features, and attributes are probably
10 the single most useful aspect of Moose. You can do a lot in a class
11 just by declaring attributes. In fact, it's quite possible to have
12 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 =head1 ATTRIBUTE OPTIONS
25 Use the C<has> function to declare an attribute:
31 has 'first_name' => ( is => 'rw' );
33 This says that all person objects have an optional read-write
34 "first_name" attribute.
36 =head2 Read-write Vs Read-only
38 The options passed to C<has> define the details of the
39 attribute. There are a lot of options you can put here, but in the
40 simplest form you just need to include C<is>, which can be either
41 C<rw> (read-write) or C<ro> (read-only).
43 (In fact, you could even omit C<is>, but that leaves you with an
44 attribute that has no accessors, which is pointless unless you're
45 doing some deep, dark magic).
47 =head2 Accessor Methods
49 Each attribute has one or more accessor methods. An accessor lets you
50 read and write the value of that attribute for an object.
52 By default, the accessor method has the same name as the attribute. If
53 you declared your attribute as C<ro> then your accessor will be
54 read-only. If you declared it read-write, you get a read-write
57 Given our Person example above, we now have a single C<first_name>
58 accessor that can read or write a person object's first name.
60 If you want, you can also explicitly specify the method names to be
61 used for reading and writing an attribute's value. This is
62 particularly handy when you'd like an attribute to be publically
63 readable, but only privately settable. For example:
67 writer => '_set_weight',
70 This might be useful if weight is calculated based on other methods,
71 for example every time the C<eat> method is called, we might adjust
72 weight. This lets us hide the implementation details of weight
73 changes, but still provide the weight value to users of the class.
75 Some people might prefer to have distinct methods for reading and
76 writing. In I<Perl Best Practices>, Damian Conway recommends that
77 reader methods start with "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 allows you to explicitly distinguish between a false or
97 undefined attribute value and an attribute which is not set. If you
98 want to be able access this information, you must define clearer and
99 predicate methods for an attribute.
101 A predicate method tells you whether or not a given attribute is
102 currently set. Note that even if the attribute was explicitly set to
103 undef or some other false value, the predicate will return true.
105 The clearer method unsets the attribute. This is I<not> the
106 same as setting the value to C<undef>, but you can only distinguish
107 between them if you define a predicate method!
109 Here's some code to illustrate the relationship between an accessor,
110 predicate, and clearer method.
118 clearer => 'clear_ssn',
119 predicate => 'has_ssn',
124 my $person = Person->new();
125 $person->has_ssn; # false
128 $person->ssn; # returns undef
129 $person->has_ssn; # true
132 $person->ssn; # returns undef
133 $person->has_ssn; # false
135 $person->ssn('123-45-6789');
136 $person->ssn; # returns '123-45-6789'
137 $person->has_ssn; # true
139 my $person2 = Person->new( ssn => '111-22-3333');
140 $person2->has_ssn; # true
142 By default, Moose does not make a predicate or clearer for you. You
143 must explicitly provide method names for these options if you want
146 =head2 Required or Not?
148 By default, all attributes are optional, and do not need to be
149 provided at object construction time. If you want to make an attribute
150 required, simply set the C<required> option to true:
157 There are a couple caveats worth mentioning in regards to what
158 required actually means.
160 Basically, all it says is that this attribute (name) must be provided
161 to the constructor. It does not say anything about its value, so it
164 If you define a clearer method on a required attribute, the clearer
165 I<will> work, so even a required attribute can be unset after object
168 This means that if you do make an attribute required, providing a
169 clearer doesn't make much sense. In some cases, it might be handy to
170 have a I<private> C<clearer> and C<predicate> for a required
173 =head2 Default and Builder Methods
175 Attributes can have default values, and Moose provides two ways to
176 specify that default.
178 In the simplest form, you simply provide a non-reference scalar value
179 for the C<default> option:
184 predicate => 'has_size',
187 If the size attribute is not provided to the constructor, then it ends
188 up being set to "medium":
190 my $person = Person->new();
191 $person->size; # medium
192 $person->has_size; # true
194 You can also provide a subroutine reference for C<default>. This
195 reference will be called a method on the object.
200 sub { ( 'small', 'medium', 'large' )[ int( rand 3 ) ] },
201 predicate => 'has_size',
204 This is dumb example, but it illustrates the point that the subroutine
205 will be called for every new object created.
207 Of course, if it's called during object construction, it may be called
208 before other attributes have been set. If your default is dependent on
209 other parts of the object's state, you can make the default c<lazy>,
210 which is covered in the next section.
212 If you want to use a reference of any sort as the default value, you
213 must return it from a subroutine. This is necessary because otherwise
214 Perl would instantiate the reference exactly once, and it would be
215 shared by all objects:
219 default => {}, # wrong!
222 Moose will throw an error if you pass a bare non-subroutine reference
225 If Moose allowed this then the default mapping attribute could easily
226 end up shared across many objects. Instead, wrap it in a subroutine
231 default => sub { {} }, # right!
234 This is a bit awkward, but it's just the way Perl works.
236 As an alternative to using a subroutine reference, you can instead
237 supply a C<builder> method for your attribute:
241 builder => '_build_size',
242 predicate => 'has_size',
246 return ( 'small', 'medium', 'large' )[ int( rand 3 ) ];
249 This has several advantages. First, it moves a chunk of code to its
250 own named method, which improves readability and code
251 organization. Second, the C<_build_size> method can be overridden in
254 We strongly recommend that you use a C<builder> instead of a
255 C<default> for anything beyond the most trivial default.
257 =head2 Laziness and lazy_build
259 Moose lets you defer attribute population by making an attribute
265 builder => '_build_size',
268 When C<lazy> is true, the attribute is not populated until the reader
269 method is called, rather than at object construction time. There are
270 several reasons you might choose to do this.
272 First, if the default value for this attribute depends on some other
273 attributes, then the attribute I<must> be C<lazy>. During object
274 construction, defaults are not generated in a predictable order, so
275 you cannot count on some other attribute being populated in a non-lazy
278 Second, there's often no reason to calculate a default before it's
279 needed. Making an attribute C<lazy> lets you defer the cost until the
280 attribute is needed. If the attribute is I<never> needed, you save
283 We recommend that you make any attribute with a builder or non-trivial
284 default C<lazy> as a matter of course.
286 To facilitate this, you can simply specify the C<lazy_build> attribute
287 option. This bundles up a number of options together:
294 This is the same as specifying all of these options:
299 builder => '_build_size',
300 clearer => 'clear_size',
301 predicate => 'has_size',
304 If your attribute name starts with an underscore (_), then the clearer
305 and predicate will as well:
317 builder => '_build__size',
318 clearer => '_clear_size',
319 predicate => '_has_size',
322 Note the doubled underscore in the builder name. Internally, Moose
323 simply prepends the attribute name with "_build_" to come up with the
326 If you don't like the names that C<lazy_build> generates, you can
327 always provide your own:
332 clearer => '_clear_size',
335 Options that you explicitly provide are always used in favor of
336 Moose's internal defaults.
338 =head2 Constructor Parameters (init_arg)
340 By default, each attribute can be passed by name to the class's
341 constructor. On occassion, you may want to use a different name for
342 the constructor parameter. You may also want to make an attribute
343 unsettable from the constructor.
345 Both of these things can be done by providing a value for the
353 Now we have an attribute named bigness, but to set it during object
354 construction we pass C<size> to the constructor.
356 Even more useful is the ability to disable setting attribute. This is
357 particularly handy for private attributes:
359 has '_genetic_code' => (
364 By setting the C<init_arg> to C<undef>, we make it impossible to set
365 this attribute when creating a new object.
367 =head2 Weak References
369 Moose has built-in support for weak references. If you set the
370 C<weak_ref> option to a true value, then it will call
371 C<Scalar::Util::weaken> whenever the attribute is set:
378 $node->parent($parent_node);
380 This is very useful when you're building objects that may contain
385 A C<trigger> is a subroutine that is called whenever the attribute is
390 trigger => \&_size_set,
394 my ( $self, $size, $meta_attr ) = @_;
396 warn $self->name, " size is now $size\n";
399 The trigger is called as a method, and receives the new value as well
400 as the L<Moose::Meta::Attribute> object for the attribute. The trigger
401 is called I<after> the value is set.
403 =head2 Attribute Types
405 Attributes can be restricted to only accept certain types:
407 has 'first_name' => (
412 This says that the first_name attribute must be a string.
414 Moose also provides a shortcut for specifying that an attribute only
415 accepts objects that do a certain role:
419 does => 'MyApp::Weapon',
422 See the L<Moose::Manual::Types> documentation for a complete
423 discussion of Moose's type system.
427 Attributes can define methods which simple delegate to their values:
429 has 'hair_color' => (
431 isa => 'Graphics::Color::RGB',
432 handles => { hair_color_hex => 'as_hex_string' },
435 This adds a new method, C<hair_color_hex>. When someone calls
436 C<hair_color_hex>, internally, the object just calls C<<
437 $self->hair_color->as_hex_string >>.
439 See L<Moose::Manual::Delegation> for more details on how to set up
442 =head2 Metaclass and traits
444 One of Moose's best features is that it can be extended in all sorts
445 of ways through the use of custom metaclasses and metaclass traits.
447 When declaring an attribute, you can declare a metaclass or a set of
448 traits for the attribute:
450 use MooseX::AttributeHelpers;
453 metaclass => 'Collection::Hash',
455 default => sub { {} },
458 In this case, the metaclass C<Collection::Hash> really refers to
459 C<MooseX::AttributeHelpers::Collection::Hash>.
461 You can also apply one or more traits to an attribute:
463 use MooseX::MetaDescription;
467 traits => ['MooseX::MetaDescription::Meta::Trait'],
469 html_widget => 'text_input',
470 serialize_as => 'element',
474 The advantage of traits is that you can mix more than one of them
475 together easily (in fact, a trait is just a role under the hood).
477 There are a number of MooseX modules on CPAN which provide useful
478 attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
479 some examples. You can also write your own metaclasses and traits. See
480 the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
482 =head1 ATTRIBUTE INHERITANCE
484 By default, a child inherits all of its parent class(es)' attributes
485 as-is. However, you can explicitly change some aspects of the
486 inherited attribute in the child class.
488 The options that can be overridden in a subclass are:
498 =item * documentation
514 To override an attribute, you simply prepend its name with a plus sign
523 has '+first_name' => (
528 Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
531 We recommend that you exercise caution when changing the type (C<isa>)
532 of an inherited attribute. It's best to only make the new type a
533 subtype of the one accepted by the parent.
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 As an alternative, you might want to look at the
561 C<MooseX::MetaDescription> module, which lets you attach a
562 "description" to each attribute. This description is a hashref that
563 can include meta-information intended for use in other code, as well
564 as documentation information.
566 =head2 The C<auto_deref> Option
568 If your attribute is an array reference or hash reference, the
569 C<auto_deref> option will make Moose de-reference the value when it is
570 returned from the reader method:
572 my %map = $object->mapping;
574 This option only works if your attribute is explicitly typed as an
577 However, we recommend that you use C<MooseX::AttributeHelpers> for
578 these types of attributes, which gives you much more control over how
579 they are accessed and manipulated.
583 Moose provides an attribute option called C<initializer>. This is
584 similar to C<builder>, except that it is I<only> called during object
587 This option is inherited from C<Class::MOP>, but we recommend that you
588 use a C<builder> (which is Moose-only) instead.
592 Dave Rolsky E<lt>autarch@urth.orgE<gt>
594 =head1 COPYRIGHT AND LICENSE
596 Copyright 2008 by Infinity Interactive, Inc.
598 L<http://www.iinteractive.com>
600 This library is free software; you can redistribute it and/or modify
601 it under the same terms as Perl itself.