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