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