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