bump copyright year to 2010
[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 attribute. There are
42 many options, but in the simplest form you just need to set C<is>, which can
43 be either C<ro> (read-only) or C<rw> (read-write). When an attribute is C<rw>,
44 you can change it by passing a value to its accessor. When an attribute is
45 C<ro>, you may only read the current value of the attribute.
46
47 In fact, you could even omit C<is>, but that gives you an attribute
48 that has no accessor. This can be useful with other attribute options,
49 such as C<handles>. However, if your attribute generates I<no>
50 accessors, Moose will issue a warning, because that usually means the
51 programmer forgot to say the attribute is read-only or read-write. If
52 you really mean to have no accessors, you can silence this warning by
53 setting C<is> to C<bare>.
54
55 =head2 Accessor methods
56
57 Each attribute has one or more accessor methods. An accessor lets you
58 read and write the value of that attribute for an object.
59
60 By default, the accessor method has the same name as the attribute. If
61 you declared your attribute as C<ro> then your accessor will be
62 read-only. If you declared it read-write, you get a read-write
63 accessor. Simple.
64
65 Given our C<Person> example above, we now have a single C<first_name>
66 accessor that can read or write a C<Person> object's C<first_name>
67 attribute's value.
68
69 If you want, you can also explicitly specify the method names to be
70 used for reading and writing an attribute's value. This is
71 particularly handy when you'd like an attribute to be publicly
72 readable, but only privately settable. For example:
73
74   has 'weight' => (
75       is     => 'ro',
76       writer => '_set_weight',
77   );
78
79 This might be useful if weight is calculated based on other methods.
80 For example, every time the C<eat> method is called, we might adjust
81 weight. This lets us hide the implementation details of weight
82 changes, but still provide the weight value to users of the class.
83
84 Some people might prefer to have distinct methods for reading and
85 writing. In I<Perl Best Practices>, Damian Conway recommends that
86 reader methods start with "get_" and writer methods start with "set_".
87
88 We can do exactly that by providing names for both the C<reader> and
89 C<writer> methods:
90
91   has 'weight' => (
92       is     => 'rw',
93       reader => 'get_weight',
94       writer => 'set_weight',
95   );
96
97 If you're thinking that doing this over and over would be insanely
98 tedious, you're right! Fortunately, Moose provides a powerful
99 extension system that lets you override the default naming
100 conventions. See L<Moose::Manual::MooseX> for more details.
101
102 =head2 Predicate and clearer methods
103
104 Moose allows you to explicitly distinguish between a false or
105 undefined attribute value and an attribute which has not been set. If
106 you want to access this information, you must define clearer and
107 predicate methods for an attribute.
108
109 A predicate method tells you whether or not a given attribute is
110 currently set. Note that an attribute can be explicitly set to
111 C<undef> or some other false value, but the predicate will return
112 true.
113
114 The clearer method unsets the attribute. This is I<not> the
115 same as setting the value to C<undef>, but you can only distinguish
116 between them if you define a predicate method!
117
118 Here's some code to illustrate the relationship between an accessor,
119 predicate, and clearer method.
120
121   package Person;
122
123   use Moose;
124
125   has 'ssn' => (
126       is        => 'rw',
127       clearer   => 'clear_ssn',
128       predicate => 'has_ssn',
129   );
130
131   ...
132
133   my $person = Person->new();
134   $person->has_ssn; # false
135
136   $person->ssn(undef);
137   $person->ssn; # returns undef
138   $person->has_ssn; # true
139
140   $person->clear_ssn;
141   $person->ssn; # returns undef
142   $person->has_ssn; # false
143
144   $person->ssn('123-45-6789');
145   $person->ssn; # returns '123-45-6789'
146   $person->has_ssn; # true
147
148   my $person2 = Person->new( ssn => '111-22-3333');
149   $person2->has_ssn; # true
150
151 By default, Moose does not make a predicate or clearer for you. You must
152 explicitly provide names for them, and then Moose will create the methods
153 for you.
154
155 =head2 Required or not?
156
157 By default, all attributes are optional, and do not need to be
158 provided at object construction time. If you want to make an attribute
159 required, simply set the C<required> option to true:
160
161   has 'name' => (
162       is       => 'ro',
163       required => 1,
164   );
165
166 There are a couple caveats worth mentioning in regards to what
167 "required" actually means.
168
169 Basically, all it says is that this attribute (C<name>) must be provided to
170 the constructor, or be lazy with either a default or a builder. It does not
171 say anything about its value, so it could be C<undef>.
172
173 If you define a clearer method on a required attribute, the clearer
174 I<will> work, so even a required attribute can be unset after object
175 construction.
176
177 This means that if you do make an attribute required, providing a
178 clearer doesn't make much sense. In some cases, it might be handy to
179 have a I<private> C<clearer> and C<predicate> for a required
180 attribute.
181
182 =head2 Default and builder methods
183
184 Attributes can have default values, and Moose provides two ways to
185 specify that default.
186
187 In the simplest form, you simply provide a non-reference scalar value
188 for the C<default> option:
189
190   has 'size' => (
191       is        => 'ro',
192       default   => 'medium',
193       predicate => 'has_size',
194   );
195
196 If the size attribute is not provided to the constructor, then it ends
197 up being set to C<medium>:
198
199   my $person = Person->new();
200   $person->size; # medium
201   $person->has_size; # true
202
203 You can also provide a subroutine reference for C<default>. This
204 reference will be called as a method on the object.
205
206   has 'size' => (
207       is => 'ro',
208       default =>
209           sub { ( 'small', 'medium', 'large' )[ int( rand 3 ) ] },
210       predicate => 'has_size',
211   );
212
213 This is a trivial example, but it illustrates the point that the subroutine
214 will be called for every new object created.
215
216 When you provide a C<default> subroutine reference, it is called as a
217 method on the object, with no additional parameters:
218
219   has 'size' => (
220       is      => 'ro',
221       default => sub {
222           my $self = shift;
223
224           return $self->height > 200 ? 'large' : 'average';
225       },
226   );
227
228 When the C<default> is called during object construction, it may be
229 called before other attributes have been set. If your default is
230 dependent on other parts of the object's state, you can make the
231 attribute C<lazy>. Laziness is covered in the next section.
232
233 If you want to use a reference of any sort as the default value, you
234 must return it from a subroutine.
235
236   has 'mapping' => (
237       is      => 'ro',
238       default => sub { {} },
239   );
240
241 This is necessary because otherwise Perl would instantiate the reference
242 exactly once, and it would be shared by all objects:
243
244   has 'mapping' => (
245       is      => 'ro',
246       default => {}, # wrong!
247   );
248
249 Moose will throw an error if you pass a bare non-subroutine reference
250 as the default.
251
252 If Moose allowed this then the default mapping attribute could easily
253 end up shared across many objects. Instead, wrap it in a subroutine
254 reference as we saw above.
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 supply a C<builder>
259 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 own named
272 method, which improves readability and code organization. Second, because this
273 is a I<named> method, it can be subclassed or provided by a role.
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 work well with 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
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 =head2 Constructor parameters (C<init_arg>)
352
353 By default, each attribute can be passed by name to the class's
354 constructor. On occasion, you may want to use a different name for
355 the constructor parameter. You may also want to make an attribute
356 unsettable via the constructor.
357
358 You can do either of these things with the C<init_arg> option:
359
360   has 'bigness' => (
361       is       => 'ro',
362       init_arg => 'size',
363   );
364
365 Now we have an attribute named "bigness", but we pass C<size> to the
366 constructor.
367
368 Even more useful is the ability to disable setting an attribute via
369 the constructor. This is particularly handy for private attributes:
370
371   has '_genetic_code' => (
372       is       => 'ro',
373       lazy     => 1,
374       builder  => '_build_genetic_code',
375       init_arg => undef,
376   );
377
378 By setting the C<init_arg> to C<undef>, we make it impossible to set
379 this attribute when creating a new object.
380
381 =head2 Weak references
382
383 Moose has built-in support for weak references. If you set the
384 C<weak_ref> option to a true value, then it will call
385 C<Scalar::Util::weaken> whenever the attribute is set:
386
387   has 'parent' => (
388       is       => 'rw',
389       weak_ref => 1,
390   );
391
392   $node->parent($parent_node);
393
394 This is very useful when you're building objects that may contain
395 circular references.
396
397 =head2 Triggers
398
399 A C<trigger> is a subroutine that is called whenever the attribute is
400 set:
401
402   has 'size' => (
403       is      => 'rw',
404       trigger => \&_size_set,
405   );
406
407   sub _size_set {
408       my ( $self, $size, $old_size ) = @_;
409
410       my $msg = $self->name;
411
412       if ( @_ > 2 ) {
413           $msg .= " - old size was $old_size";
414       }
415
416       $msg .= " - size is now $size";
417       warn $msg;
418   }
419
420 The trigger is called I<after> an attribute's value is set. It is
421 called as a method on the object, and receives the new and old values as
422 its arguments. If the attribute had not previously been set at all,
423 then only the new value is passed. This lets you distinguish between
424 the case where the attribute had no value versus when the old value was C<undef>.
425
426 This differs from an C<after> method modifier in two ways. First, a
427 trigger is only called when the attribute is set, as opposed to
428 whenever the accessor method is called (for reading or
429 writing). Second, it is also called when an attribute's value is
430 passed to the constructor.
431
432 However, triggers are I<not> called when an attribute is populated
433 from a C<default> or C<builder>
434
435 =head2 Attribute types
436
437 Attributes can be restricted to only accept certain types:
438
439   has 'first_name' => (
440       is  => 'ro',
441       isa => 'Str',
442   );
443
444 This says that the C<first_name> attribute must be a string.
445
446 Moose also provides a shortcut for specifying that an attribute only
447 accepts objects that do a certain role:
448
449   has 'weapon' => (
450       is   => 'rw',
451       does => 'MyApp::Weapon',
452   );
453
454 See the L<Moose::Manual::Types> documentation for a complete
455 discussion of Moose's type system.
456
457 =head2 Delegation
458
459 An attribute can define methods which simply delegate to its value:
460
461   has 'hair_color' => (
462       is      => 'ro',
463       isa     => 'Graphics::Color::RGB',
464       handles => { hair_color_hex => 'as_hex_string' },
465   );
466
467 This adds a new method, C<hair_color_hex>. When someone calls
468 C<hair_color_hex>, internally, the object just calls C<<
469 $self->hair_color->as_hex_string >>.
470
471 See L<Moose::Manual::Delegation> for documentation on how to set up
472 delegation methods.
473
474 =head2 Attribute traits and metaclasses
475
476 One of Moose's best features is that it can be extended in all sorts of ways
477 through the use of metaclass traits and custom metaclasses.
478
479 You can apply one or more traits to an attribute:
480
481   use MooseX::MetaDescription;
482
483   has 'size' => (
484       is          => 'ro',
485       traits      => ['MooseX::MetaDescription::Meta::Trait'],
486       description => {
487           html_widget  => 'text_input',
488           serialize_as => 'element',
489       },
490   );
491
492 The advantage of traits is that you can mix more than one of them
493 together easily (in fact, a trait is just a role under the hood).
494
495 There are a number of MooseX modules on CPAN which provide useful
496 attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
497 some examples. You can also write your own metaclasses and traits. See
498 the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
499
500 =head2 Native Delegations
501
502 Native delegations allow you to delegate to standard Perl data structures as
503 if they were objects.
504
505 For example, we can pretend that an array reference has methods like
506 C<push()>, C<shift()>, C<map()>, C<count()>, and more.
507
508   has 'options' => (
509       traits  => ['Array'],
510       is      => 'ro',
511       isa     => 'ArrayRef[Str]',
512       default => sub { [] },
513       handles => {
514           all_options    => 'elements',
515           add_option     => 'push',
516           map_options    => 'map',
517           option_count   => 'count',
518           sorted_options => 'sort',
519       },
520   );
521
522 See L<Moose::Manual::Delegation> for more details.
523
524 =head1 ATTRIBUTE INHERITANCE
525
526 By default, a child inherits all of its parent class(es)' attributes
527 as-is. However, you can change most aspects of the inherited attribute in the
528 child class. You cannot change any of its associated method names (reader,
529 writer, predicate, etc).
530
531 To override an attribute, you simply prepend its name with a plus sign
532 (C<+>):
533
534   package LazyPerson;
535
536   use Moose;
537
538   extends 'Person';
539
540   has '+first_name' => (
541       lazy    => 1,
542       default => 'Bill',
543   );
544
545 Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
546 to C<'Bill'>.
547
548 We recommend that you exercise caution when changing the type (C<isa>)
549 of an inherited attribute.
550
551 =head1 MULTIPLE ATTRIBUTE SHORTCUTS
552
553 If you have a number of attributes that differ only by name, you can declare
554 them all at once:
555
556   package Point;
557
558   use Moose;
559
560   has [ 'x', 'y' ] => ( is => 'ro', isa => 'Int' );
561
562 Also, because C<has> is just a function call, you can call it in a loop:
563
564   for my $name ( qw( x y ) ) {
565       my $builder = '_build_' . $name;
566       has $name => ( is => 'ro', isa => 'Int', builder => $builder );
567   }
568
569 =head1 MORE ON ATTRIBUTES
570
571 Moose attributes are a big topic, and this document glosses over a few
572 aspects. We recommend that you read the L<Moose::Manual::Delegation>
573 and L<Moose::Manual::Types> documents to get a more complete
574 understanding of attribute features.
575
576 =head1 A FEW MORE OPTIONS
577
578 Moose has lots of attribute options. The ones listed below are
579 superseded by some more modern features, but are covered for the sake
580 of completeness.
581
582 =head2 The C<documentation> option
583
584 You can provide a piece of documentation as a string for an attribute:
585
586   has 'first_name' => (
587       is            => 'rw',
588       documentation => q{The person's first (personal) name},
589   );
590
591 Moose does absolutely nothing with this information other than store
592 it.
593
594 =head2 The C<auto_deref> option
595
596 If your attribute is an array reference or hash reference, the
597 C<auto_deref> option will make Moose dereference the value when it is
598 returned from the reader method:
599
600   my %map = $object->mapping;
601
602 This option only works if your attribute is explicitly typed as an
603 C<ArrayRef> or C<HashRef>.
604
605 However, we recommend that you use L<Moose::Meta::Attribute::Native> traits
606 for these types of attributes, which gives you much more control over how
607 they are accessed and manipulated.
608
609 =head2 Initializer
610
611 Moose provides an attribute option called C<initializer>. This is called when
612 the attribute's value is being set in the constructor, and lets you change the
613 value before it is set.
614
615 =head1 AUTHOR
616
617 Dave Rolsky E<lt>autarch@urth.orgE<gt>
618
619 =head1 COPYRIGHT AND LICENSE
620
621 Copyright 2009-2010 by Infinity Interactive, Inc.
622
623 L<http://www.iinteractive.com>
624
625 This library is free software; you can redistribute it and/or modify
626 it under the same terms as Perl itself.
627
628 =cut