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