5 Moose::Manual::Attributes - 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 C<Person> object has a first name and
16 last name". Attributes can be optional, so that we can say "some C<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 C<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 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>
44 (read-only). C<rw> permits mutation of the attribute's value using the
45 accessor. C<ro> does not; you may only read the current value of the
48 (In fact, you could even omit C<is>, but that gives you an attribute
49 that has no accessors, which is pointless unless you're doing some
52 =head2 Accessor methods
54 Each attribute has one or more accessor methods. An accessor lets you
55 read and write the value of that attribute for an object.
57 By default, the accessor method has the same name as the attribute. If
58 you declared your attribute as C<ro> then your accessor will be
59 read-only. If you declared it read-write, you get a read-write
62 Given our C<Person> example above, we now have a single C<first_name>
63 accessor that can read or write a C<Person> object's C<first_name>
66 If you want, you can also explicitly specify the method names to be
67 used for reading and writing an attribute's value. This is
68 particularly handy when you'd like an attribute to be publicly
69 readable, but only privately settable. For example:
73 writer => '_set_weight',
76 This might be useful if weight is calculated based on other methods.
77 For example, every time the C<eat> method is called, we might adjust
78 weight. This lets us hide the implementation details of weight
79 changes, but still provide the weight value to users of the class.
81 Some people might prefer to have distinct methods for reading and
82 writing. In I<Perl Best Practices>, Damian Conway recommends that
83 reader methods start with "get_" and writer methods start with "set_".
85 We can do exactly that by providing names for both the C<reader> and
90 reader => 'get_weight',
91 writer => 'set_weight',
94 If you're thinking that doing this over and over would be insanely
95 tedious, you're right! Fortunately, Moose provides a powerful
96 extension system that lets you override the default naming
97 conventions. See L<Moose::Manual::MooseX> for more details.
99 =head2 Predicate and clearer methods
101 Moose allows you to explicitly distinguish between a false or
102 undefined attribute value and an attribute which has not been set. If
103 you want to access this information, you must define clearer and
104 predicate methods for an attribute.
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
108 C<undef> or some other false value, but the predicate will return
111 The clearer method unsets the attribute. This is I<not> the
112 same as setting the value to C<undef>, but you can only distinguish
113 between them if you define a predicate method!
115 Here's some code to illustrate the relationship between an accessor,
116 predicate, and clearer method.
124 clearer => 'clear_ssn',
125 predicate => 'has_ssn',
130 my $person = Person->new();
131 $person->has_ssn; # false
134 $person->ssn; # returns undef
135 $person->has_ssn; # true
138 $person->ssn; # returns undef
139 $person->has_ssn; # false
141 $person->ssn('123-45-6789');
142 $person->ssn; # returns '123-45-6789'
143 $person->has_ssn; # true
145 my $person2 = Person->new( ssn => '111-22-3333');
146 $person2->has_ssn; # true
148 By default, Moose does not make a predicate or clearer for you. You must
149 explicitly provide names for them, and then Moose will create the methods
152 =head2 Required or not?
154 By default, all attributes are optional, and do not need to be
155 provided at object construction time. If you want to make an attribute
156 required, simply set the C<required> option to true:
163 There are a couple caveats worth mentioning in regards to what
164 "required" actually means.
166 Basically, all it says is that this attribute (C<name>) must be provided to
167 the constructor, or be lazy with either a default or a builder. It does not
168 say anything about its value, so it could be C<undef>.
170 If you define a clearer method on a required attribute, the clearer
171 I<will> work, so even a required attribute can be unset after object
174 This means that if you do make an attribute required, providing a
175 clearer doesn't make much sense. In some cases, it might be handy to
176 have a I<private> C<clearer> and C<predicate> for a required
179 =head2 Default and builder methods
181 Attributes can have default values, and Moose provides two ways to
182 specify that default.
184 In the simplest form, you simply provide a non-reference scalar value
185 for the C<default> option:
190 predicate => 'has_size',
193 If the size attribute is not provided to the constructor, then it ends
194 up being set to C<medium>:
196 my $person = Person->new();
197 $person->size; # medium
198 $person->has_size; # true
200 You can also provide a subroutine reference for C<default>. This
201 reference will be called as a method on the object.
206 sub { ( 'small', 'medium', 'large' )[ int( rand 3 ) ] },
207 predicate => 'has_size',
210 This is dumb example, but it illustrates the point that the subroutine
211 will be called for every new object created.
213 When you provide a C<default> subroutine reference, it is called as a
214 method on the object, with no additional parameters:
221 return $self->height > 200 ? 'big' : 'average';
225 When the C<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 C<lazy>. Laziness is covered in the next section.
230 If you want to use a reference of any sort as the default value, you
231 must return it from a subroutine. This is necessary because otherwise
232 Perl would instantiate the reference exactly once, and it would be
233 shared by all objects:
237 default => {}, # wrong!
240 Moose will throw an error if you pass a bare non-subroutine reference
243 If Moose allowed this then the default mapping attribute could easily
244 end up shared across many objects. Instead, wrap it in a subroutine
249 default => sub { {} }, # right!
252 This is a bit awkward, but it's just the way Perl works.
254 As an alternative to using a subroutine reference, you can instead
255 supply a C<builder> method for your attribute:
259 builder => '_build_size',
260 predicate => 'has_size',
264 return ( 'small', 'medium', 'large' )[ int( rand 3 ) ];
267 This has several advantages. First, it moves a chunk of code to its
268 own named method, which improves readability and code
271 We strongly recommend that you use a C<builder> instead of a
272 C<default> for anything beyond the most trivial default.
274 A C<builder>, just like a C<default>, is called as a method on the
275 object with no additional parameters.
277 =head3 Builders allow subclassing
279 Because the C<builder> is called I<by name>, it goes through Perl's
280 method resolution. This means that builder methods are both
281 inheritable and overridable.
283 If we subclass our C<Person> class, we can override C<_build_size>:
290 sub _build_size { return 'small' }
292 =head3 Builders can be composed from roles
294 Because builders are called by name, they work well with roles. For
295 example, a role could provide an attribute but require that the
296 consuming class provide the C<builder>:
301 requires '_build_size';
306 builder => '_build_size',
314 sub _build_size { return 'small' }
316 Roles are covered in L<Moose::Manual::Roles>.
318 =head2 Laziness and C<lazy_build>
320 Moose lets you defer attribute population by making an attribute
326 builder => '_build_size',
329 When C<lazy> is true, the default is not generated until the reader
330 method is called, rather than at object construction time. There are
331 several reasons you might choose to do this.
333 First, if the default value for this attribute depends on some other
334 attributes, then the attribute I<must> be C<lazy>. During object
335 construction, defaults are not generated in a predictable order, so
336 you cannot count on some other attribute being populated when
337 generating a default.
339 Second, there's often no reason to calculate a default before it's
340 needed. Making an attribute C<lazy> lets you defer the cost until the
341 attribute is needed. If the attribute is I<never> needed, you save
344 We recommend that you make any attribute with a builder or non-trivial
345 default C<lazy> as a matter of course.
347 To facilitate this, you can simply specify the C<lazy_build> attribute
348 option. This bundles up a number of options together:
355 This is the same as specifying all of these options:
360 builder => '_build_size',
361 clearer => 'clear_size',
362 predicate => 'has_size',
365 If your attribute name starts with an underscore (C<_>), then the clearer
366 and predicate will as well:
378 builder => '_build__size',
379 clearer => '_clear_size',
380 predicate => '_has_size',
383 Note the doubled underscore in the builder name. Internally, Moose
384 simply prepends the attribute name with "_build_" to come up with the
387 If you don't like the names that C<lazy_build> generates, you can
388 always provide your own:
393 clearer => '_clear_size',
396 Options that you explicitly provide are always used in favor of
397 Moose's internal defaults.
399 =head2 Constructor parameters (C<init_arg>)
401 By default, each attribute can be passed by name to the class's
402 constructor. On occasion, you may want to use a different name for
403 the constructor parameter. You may also want to make an attribute
404 unsettable via the constructor.
406 Both of these goals can be accomplished with the C<init_arg> option:
413 Now we have an attribute named "bigness", but we pass C<size> to the
416 Even more useful is the ability to disable setting an attribute via
417 the constructor. This is particularly handy for private attributes:
419 has '_genetic_code' => (
425 By setting the C<init_arg> to C<undef>, we make it impossible to set
426 this attribute when creating a new object.
428 =head2 Weak references
430 Moose has built-in support for weak references. If you set the
431 C<weak_ref> option to a true value, then it will call
432 C<Scalar::Util::weaken> whenever the attribute is set:
439 $node->parent($parent_node);
441 This is very useful when you're building objects that may contain
446 A C<trigger> is a subroutine that is called whenever the attribute is
451 trigger => \&_size_set,
455 my ( $self, $size ) = @_;
457 warn $self->name, " size is now $size\n";
460 The trigger is called as a method, and receives the new value as its argument.
461 The trigger is called I<after> the value is set.
463 This differs from an C<after> method modifier in two ways. First, a
464 trigger is only called when the attribute is set, as opposed to
465 whenever the accessor method is called (for reading or
466 writing). Second, it is also called when an attribute's value is
467 passed to the constructor.
469 However, triggers are I<not> called when an attribute is populated
470 from a C<default> or C<builder>
472 =head2 Attribute types
474 Attributes can be restricted to only accept certain types:
476 has 'first_name' => (
481 This says that the C<first_name> attribute must be a string.
483 Moose also provides a shortcut for specifying that an attribute only
484 accepts objects that do a certain role:
488 does => 'MyApp::Weapon',
491 See the L<Moose::Manual::Types> documentation for a complete
492 discussion of Moose's type system.
496 An attribute can define methods which simply delegate to its value:
498 has 'hair_color' => (
500 isa => 'Graphics::Color::RGB',
501 handles => { hair_color_hex => 'as_hex_string' },
504 This adds a new method, C<hair_color_hex>. When someone calls
505 C<hair_color_hex>, internally, the object just calls C<<
506 $self->hair_color->as_hex_string >>.
508 See L<Moose::Manual::Delegation> for documentation on how to set up
511 =head2 Metaclass and traits
513 One of Moose's best features is that it can be extended in all sorts
514 of ways through the use of custom metaclasses and metaclass traits.
516 When declaring an attribute, you can declare a metaclass or a set of
517 traits for the attribute:
519 use MooseX::AttributeHelpers;
522 metaclass => 'Collection::Hash',
524 default => sub { {} },
527 In this case, the metaclass C<Collection::Hash> really refers to
528 L<MooseX::AttributeHelpers::Collection::Hash>.
530 You can also apply one or more traits to an attribute:
532 use MooseX::MetaDescription;
536 traits => ['MooseX::MetaDescription::Meta::Trait'],
538 html_widget => 'text_input',
539 serialize_as => 'element',
543 The advantage of traits is that you can mix more than one of them
544 together easily (in fact, a trait is just a role under the hood).
546 There are a number of MooseX modules on CPAN which provide useful
547 attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
548 some examples. You can also write your own metaclasses and traits. See
549 the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
551 =head1 ATTRIBUTE INHERITANCE
553 By default, a child inherits all of its parent class(es)' attributes
554 as-is. However, you can explicitly change some aspects of the
555 inherited attribute in the child class.
557 The options that can be overridden in a subclass are:
567 =item * documentation
583 To override an attribute, you simply prepend its name with a plus sign
592 has '+first_name' => (
597 Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
600 We recommend that you exercise caution when changing the type (C<isa>)
601 of an inherited attribute.
603 =head1 MORE ON ATTRIBUTES
605 Moose attributes are a big topic, and this document glosses over a few
606 aspects. We recommend that you read the L<Moose::Manual::Delegation>
607 and L<Moose::Manual::Types> documents to get a more complete
608 understanding of attribute features.
610 =head1 A FEW MORE OPTIONS
612 Moose has lots of attribute options. The ones listed below are
613 superseded by some more modern features, but are covered for the sake
616 =head2 The C<documentation> option
618 You can provide a piece of documentation as a string for an attribute:
620 has 'first_name' => (
622 documentation => q{The person's first (personal) name},
625 Moose does absolutely nothing with this information other than store
628 =head2 The C<auto_deref> option
630 If your attribute is an array reference or hash reference, the
631 C<auto_deref> option will make Moose dereference the value when it is
632 returned from the reader method:
634 my %map = $object->mapping;
636 This option only works if your attribute is explicitly typed as an
637 C<ArrayRef> or C<HashRef>.
639 However, we recommend that you use L<MooseX::AttributeHelpers> for
640 these types of attributes, which gives you much more control over how
641 they are accessed and manipulated.
645 Moose provides an attribute option called C<initializer>. This is
646 similar to C<builder>, except that it is I<only> called during object
649 This option is inherited from L<Class::MOP>, but we recommend that you
650 use a C<builder> (which is Moose-only) instead.
654 Dave Rolsky E<lt>autarch@urth.orgE<gt>
656 =head1 COPYRIGHT AND LICENSE
658 Copyright 2009 by Infinity Interactive, Inc.
660 L<http://www.iinteractive.com>
662 This library is free software; you can redistribute it and/or modify
663 it under the same terms as Perl itself.