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