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