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