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