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