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