Lots of cleanup in the text.
[gitmo/Moose.git] / lib / Moose / Manual / Attributes.pod
1 =pod
2
3 =head1 NAME
4
5 Moose::Manual::Attribute - Object attributes with Moose
6
7 =head1 INTRODUCTION
8
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.
13
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)".
18
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.
22
23 =head1 ATTRIBUTE OPTIONS
24
25 Use the C<has> function to declare an attribute:
26
27   package Person;
28
29   use Moose;
30
31   has 'first_name' => ( is => 'rw' );
32
33 This says that all person objects have an optional read-write
34 "first_name" attribute.
35
36 =head2 Read-write Vs Read-only
37
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).
42
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).
46
47 =head2 Accessor Methods
48
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.
51
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
55 accessor. Simple.
56
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.
59
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:
64
65   has 'weight' =>
66       ( is     => 'rw',
67         writer => '_set_weight',
68       );
69
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.
74
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_".
78
79 We can do exactly that by providing names for both the C<reader> and
80 C<writer> methods:
81
82   has 'weight' =>
83       ( is     => 'rw',
84         reader => 'get_weight',
85         writer => 'set_weight',
86       );
87
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
92 details.
93
94 =head2 Predicate and Clearer Methods
95
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.
100
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.
104
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!
108
109 Here's some code to illustrate the relationship between an accessor,
110 predicate, and clearer method.
111
112   package Person;
113
114   use Moose;
115
116   has 'ssn' =>
117       ( is        => 'rw',
118         clearer   => 'clear_ssn',
119         predicate => 'has_ssn',
120       );
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
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
144 them.
145
146 =head2 Required or Not?
147
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:
151
152   has 'name' =>
153       ( is       => 'rw',
154         required => 1,
155       );
156
157 There are a couple caveats worth mentioning in regards to what
158 required actually means.
159
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
162 could be C<undef>.
163
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
166 construction.
167
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
171 attribute.
172
173 =head2 Default and Builder Methods
174
175 Attributes can have default values, and Moose provides two ways to
176 specify that default.
177
178 In the simplest form, you simply provide a non-reference scalar value
179 for the C<default> option:
180
181   has 'size' =>
182       ( is        => 'rw',
183         default   => 'medium',
184         predicate => 'has_size',
185       );
186
187 If the size attribute is not provided to the constructor, then it ends
188 up being set to "medium":
189
190   my $person = Person->new();
191   $person->size; # medium
192   $person->has_size; # true
193
194 You can also provide a subroutine reference for C<default>. This
195 reference will be called a method on the object.
196
197   has 'size' =>
198       ( is        => 'rw',
199         default   =>
200             sub { ('small', 'medium', 'large')[ int( rand 3 ) ] },
201         predicate => 'has_size',
202       );
203
204 This is dumb example, but it illustrates the point that the subroutine
205 will be called for every new object created.
206
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.
211
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:
216
217   has 'mapping' =>
218       ( is      => 'rw',
219         default => {}, # wrong!
220       );
221
222 Moose will throw an error if you pass a bare non-subroutine reference
223 as the default.
224
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
227 reference:
228
229   has 'mapping' =>
230       ( is      => 'rw',
231         default => sub { {} }, # right!
232       );
233
234 This is a bit awkward, but it's just the way Perl works.
235
236 As an alternative to using a subroutine reference, you can instead
237 supply a C<builder> method for your attribute:
238
239   has 'size' =>
240       ( is        => 'rw',
241         builder   => '_build_size',
242         predicate => 'has_size',
243       );
244
245   sub _build_size {
246       return ('small', 'medium', 'large')[ int( rand 3 ) ];
247   }
248
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
252 subclasses.
253
254 We strongly recommend that you use a C<builder> instead of a
255 C<default> for anything beyond the most trivial default.
256
257 =head2 Laziness and lazy_build
258
259 Moose lets you defer attribute population by making an attribute
260 C<lazy>:
261
262   has 'size' =>
263       ( is        => 'rw',
264         lazy      => 1,
265         builder   => '_build_size',
266       );
267
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.
271
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
276 default subroutine.
277
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
281 some CPU time.
282
283 We recommend that you make any attribute with a builder or non-trivial
284 default C<lazy> as a matter of course.
285
286 To facilitate this, you can simply specify the C<lazy_build> attribute
287 option. This bundles up a number of options together:
288
289   has 'size' =>
290       ( is         => 'rw',
291         lazy_build => 1,
292       );
293
294 This is the same as specifying all of these options:
295
296   has 'size' =>
297       ( is        => 'rw',
298         lazy      => 1,
299         builder   => '_build_size',
300         clearer   => 'clear_size',
301         predicate => 'has_size',
302       );
303
304 If your attribute name starts with an underscore (_), then the clearer
305 and predicate will as well:
306
307   has '_size' =>
308       ( is         => 'rw',
309         lazy_build => 1,
310       );
311
312 becomes:
313
314   has '_size' =>
315       ( is        => 'rw',
316         lazy      => 1,
317         builder   => '_build__size',
318         clearer   => '_clear_size',
319         predicate => '_has_size',
320       );
321
322 Note the doubled underscore in the builder name. Internally, Moose
323 simply prepends the attribute name with "_build_" to come up with the
324 builder name.
325
326 If you don't like the names that C<lazy_build> generates, you can
327 always provide your own:
328
329   has 'size' =>
330       ( is         => 'rw',
331         lazy_build => 1,
332         clearer    => '_clear_size',
333       );
334
335 Options that you explicitly provide are always used in favor of
336 Moose's internal defaults.
337
338 =head2 Constructor Parameters (init_arg)
339
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.
344
345 Both of these things can be done by providing a value for the
346 C<init_arg> option:
347
348   has 'bigness' =>
349       ( is       => 'rw',
350         init_arg => 'size',
351       );
352
353 Now we have an attribute named bigness, but to set it during object
354 construction we pass C<size> to the constructor.
355
356 Even more useful is the ability to disable setting attribute. This is
357 particularly handy for private attributes:
358
359   has '_genetic_code' =>
360      ( is       => 'rw',
361        init_arg => undef,
362      );
363
364 By setting the C<init_arg> to C<undef>, we make it impossible to set
365 this attribute when creating a new object.
366
367 =head2 Weak References
368
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:
372
373   has 'parent' =>
374       ( is       => 'rw',
375         weak_ref => 1,
376       );
377
378   $node->parent($parent_node);
379
380 This is very useful when you're building objects that may contain
381 circular references.
382
383 =head2 Triggers
384
385 A C<trigger> is a subroutine that is called whenever the attribute is
386 set:
387
388   has 'size' =>
389       ( is      => 'rw',
390         trigger => \&_size_set,
391       );
392
393   sub _size_set {
394       my ( $self, $size, $meta_attr ) = @_;
395
396       warn $self->name, " size is now $size\n";
397   }
398
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.
402
403 =head2 Attribute Types
404
405 Attributes can be restricted to only accept certain types:
406
407   has 'first_name' =>
408       ( is  => 'rw',
409         isa => 'Str',
410       );
411
412 This says that the first_name attribute must be a string.
413
414 Moose also provides a shortcut for specifying that an attribute only
415 accepts objects that do a certain role:
416
417   has 'weapon' =>
418      ( is   => 'rw',
419        does => 'MyApp::Weapon',
420      );
421
422 See the L<Moose::Manual::Types> documentation for a complete
423 discussion of Moose's type system.
424
425 =head2 Delegation
426
427 Attributes can define methods which simple delegate to their values:
428
429   has 'hair_color' =>
430       ( is      => 'rw',
431         isa     => 'Graphics::Color::RGB',
432         handles => { hair_color_hex => 'as_hex_string' },
433       );
434
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 >>.
438
439 See L<Moose::Manual::Delegation> for more details on how to set up
440 delegation methods.
441
442 =head2 Metaclass and traits
443
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.
446
447 When declaring an attribute, you can declare a metaclass or a set of
448 traits for the attribute:
449
450   use MooseX::AttributeHelpers;
451
452   has 'mapping' =>
453       ( metaclass => 'Collection::Hash',
454         is        => 'ro',
455         default   => sub { {} },
456       );
457
458 In this case, the metaclass C<Collection::Hash> really refers to
459 C<MooseX::AttributeHelpers::Collection::Hash>.
460
461 You can also apply one or more traits to an attribute:
462
463   use MooseX::MetaDescription;
464
465   has 'size' =>
466       ( is          => 'rw',
467         traits      => [ 'MooseX::MetaDescription::Meta::Trait' ],
468         description => { html_widget  => 'text_input',
469                          serialize_as => 'element',
470                        },
471       );
472
473 The advantage of traits is that you can mix more than one of them
474 together easily (in fact, a trait is just a role under the hood).
475
476 There are a number of MooseX modules on CPAN which provide useful
477 attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
478 some examples. You can also write your own metaclasses and traits. See
479 the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
480
481 =head2 Attribute Inheritance
482
483 By default, a child inherits all of its parent class(es)' attributes
484 as-is. However, you can explicitly change some aspects of the
485 inherited attribute in the child class.
486
487 The options that can be overridden in a subclass are:
488
489 =over 4
490
491 =item * default
492
493 =item * coerce
494
495 =item * required
496
497 =item * documentation
498
499 =item * lazy
500
501 =item * isa
502
503 =item * handles
504
505 =item * builder
506
507 =item * metaclass
508
509 =item * traits
510
511 =back
512
513 To override an attribute, you simply prepend its name with a plus sign
514 (+):
515
516   package LazyPerson;
517
518   use Moose;
519
520   extends 'Person';
521
522   has '+first_name' =>
523       ( lazy    => 1,
524         default => 'Bill',
525       );
526
527 Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
528 to C<'Bill'>.
529
530 We recommend that you exercise caution when changing the type (C<isa>)
531 of an inherited attribute. It's best to only make the new type a
532 subtype of the one accepted by the parent.
533
534 =head2 The C<documentation> option
535
536 You can provide a piece of documentation as a string for an attribute:
537
538   has 'first_name' =>
539       ( is            => 'rw',
540         documentation => q{The person's first (personal) name},
541       );
542
543 Moose does absolutely nothing with this information other than store
544 it.
545
546 As an alternative, you might want to look at the
547 C<MooseX::MetaDescription> module, which lets you attach a
548 "description" to each attribute. This description is a hashref that
549 can include meta-information intended for use in other code, as well
550 as documentation information.
551
552 =head2 The C<auto_deref> Option
553
554 If your attribute is an array reference or hash reference, the
555 C<auto_deref> option will make Moose de-reference the value when it is
556 returned from the reader method:
557
558   my %map = $object->mapping;
559
560 This option only works if your attribute is explicitly typed as an
561 ArrayRef or HashRef.
562
563 However, we recommend that you use C<MooseX::AttributeHelpers> for
564 these types of attributes, which gives you much more control over how
565 they are accessed and manipulated.
566
567 =head2 Initializer
568
569 Moose provides an attribute option called C<initializer>. This is
570 similar to C<builder>, except that it is I<only> called during object
571 construction.
572
573 This option is inherited from C<Class::MOP>, but we recommend that you
574 use a C<builder> (which is Moose-only) instead.
575
576 =head1 MORE ON ATTRIBUTES
577
578 Moose attributes are a big topic, and this document glosses over a few
579 topics. We recommend that you read the L<Moose::Manual::Delegation>
580 and L<Moose::Manual::Types> documents to get a more complete
581 understanding of attribute features.
582
583 =head1 AUTHOR
584
585 Dave Rolsky E<lt>autarch@urth.orgE<gt>
586
587 =head1 COPYRIGHT AND LICENSE
588
589 Copyright 2008 by Infinity Interactive, Inc.
590
591 L<http://www.iinteractive.com>
592
593 This library is free software; you can redistribute it and/or modify
594 it under the same terms as Perl itself.
595
596 =cut