Include discussion of is => bare
[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). C<rw> permits mutation of the attribute's value using the
45 accessor. C<ro> does not; you may only read the current value of the
46 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 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 ) = @_;
460
461       warn $self->name, " size is now $size\n";
462   }
463
464 The trigger is called as a method, and receives the new value as its argument.
465 The trigger is called I<after> the value is set.
466
467 This differs from an C<after> method modifier in two ways. First, a
468 trigger is only called when the attribute is set, as opposed to
469 whenever the accessor method is called (for reading or
470 writing). Second, it is also called when an attribute's value is
471 passed to the constructor.
472
473 However, triggers are I<not> called when an attribute is populated
474 from a C<default> or C<builder>
475
476 =head2 Attribute types
477
478 Attributes can be restricted to only accept certain types:
479
480   has 'first_name' => (
481       is  => 'ro',
482       isa => 'Str',
483   );
484
485 This says that the C<first_name> attribute must be a string.
486
487 Moose also provides a shortcut for specifying that an attribute only
488 accepts objects that do a certain role:
489
490   has 'weapon' => (
491       is   => 'rw',
492       does => 'MyApp::Weapon',
493   );
494
495 See the L<Moose::Manual::Types> documentation for a complete
496 discussion of Moose's type system.
497
498 =head2 Delegation
499
500 An attribute can define methods which simply delegate to its value:
501
502   has 'hair_color' => (
503       is      => 'ro',
504       isa     => 'Graphics::Color::RGB',
505       handles => { hair_color_hex => 'as_hex_string' },
506   );
507
508 This adds a new method, C<hair_color_hex>. When someone calls
509 C<hair_color_hex>, internally, the object just calls C<<
510 $self->hair_color->as_hex_string >>.
511
512 See L<Moose::Manual::Delegation> for documentation on how to set up
513 delegation methods.
514
515 =head2 Metaclass and traits
516
517 One of Moose's best features is that it can be extended in all sorts
518 of ways through the use of custom metaclasses and metaclass traits.
519
520 When declaring an attribute, you can declare a metaclass or a set of
521 traits for the attribute:
522
523   use MooseX::AttributeHelpers;
524
525   has 'mapping' => (
526       metaclass => 'Collection::Hash',
527       is        => 'ro',
528       default   => sub { {} },
529   );
530
531 In this case, the metaclass C<Collection::Hash> really refers to
532 L<MooseX::AttributeHelpers::Collection::Hash>.
533
534 You can also apply one or more traits to an attribute:
535
536   use MooseX::MetaDescription;
537
538   has 'size' => (
539       is          => 'ro',
540       traits      => ['MooseX::MetaDescription::Meta::Trait'],
541       description => {
542           html_widget  => 'text_input',
543           serialize_as => 'element',
544       },
545   );
546
547 The advantage of traits is that you can mix more than one of them
548 together easily (in fact, a trait is just a role under the hood).
549
550 There are a number of MooseX modules on CPAN which provide useful
551 attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
552 some examples. You can also write your own metaclasses and traits. See
553 the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
554
555 =head1 ATTRIBUTE INHERITANCE
556
557 By default, a child inherits all of its parent class(es)' attributes
558 as-is. However, you can explicitly change some aspects of the
559 inherited attribute in the child class.
560
561 The options that can be overridden in a subclass are:
562
563 =over 4
564
565 =item * default
566
567 =item * coerce
568
569 =item * required
570
571 =item * documentation
572
573 =item * lazy
574
575 =item * isa
576
577 =item * handles
578
579 =item * builder
580
581 =item * metaclass
582
583 =item * traits
584
585 =back
586
587 To override an attribute, you simply prepend its name with a plus sign
588 (C<+>):
589
590   package LazyPerson;
591
592   use Moose;
593
594   extends 'Person';
595
596   has '+first_name' => (
597       lazy    => 1,
598       default => 'Bill',
599   );
600
601 Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
602 to C<'Bill'>.
603
604 We recommend that you exercise caution when changing the type (C<isa>)
605 of an inherited attribute.
606
607 =head1 MORE ON ATTRIBUTES
608
609 Moose attributes are a big topic, and this document glosses over a few
610 aspects. We recommend that you read the L<Moose::Manual::Delegation>
611 and L<Moose::Manual::Types> documents to get a more complete
612 understanding of attribute features.
613
614 =head1 A FEW MORE OPTIONS
615
616 Moose has lots of attribute options. The ones listed below are
617 superseded by some more modern features, but are covered for the sake
618 of completeness.
619
620 =head2 The C<documentation> option
621
622 You can provide a piece of documentation as a string for an attribute:
623
624   has 'first_name' => (
625       is            => 'rw',
626       documentation => q{The person's first (personal) name},
627   );
628
629 Moose does absolutely nothing with this information other than store
630 it.
631
632 =head2 The C<auto_deref> option
633
634 If your attribute is an array reference or hash reference, the
635 C<auto_deref> option will make Moose dereference the value when it is
636 returned from the reader method:
637
638   my %map = $object->mapping;
639
640 This option only works if your attribute is explicitly typed as an
641 C<ArrayRef> or C<HashRef>.
642
643 However, we recommend that you use L<MooseX::AttributeHelpers> for
644 these types of attributes, which gives you much more control over how
645 they are accessed and manipulated.
646
647 =head2 Initializer
648
649 Moose provides an attribute option called C<initializer>. This is
650 similar to C<builder>, except that it is I<only> called during object
651 construction.
652
653 This option is inherited from L<Class::MOP>, but we recommend that you
654 use a C<builder> (which is Moose-only) instead.
655
656 =head1 AUTHOR
657
658 Dave Rolsky E<lt>autarch@urth.orgE<gt>
659
660 =head1 COPYRIGHT AND LICENSE
661
662 Copyright 2009 by Infinity Interactive, Inc.
663
664 L<http://www.iinteractive.com>
665
666 This library is free software; you can redistribute it and/or modify
667 it under the same terms as Perl itself.
668
669 =cut