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