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