add a function to more easily create metaclass/trait aliases
[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
214This is dumb example, but it illustrates the point that the subroutine
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 {
c2685d20 459 my ( $self, $size ) = @_;
0b9488c8 460
d4b96efa 461 warn $self->name, " size is now $size\n";
0b9488c8 462 }
463
c2685d20 464The trigger is called as a method, and receives the new value as its argument.
465The trigger is called I<after> the value is set.
0b9488c8 466
d76a67a8 467This differs from an C<after> method modifier in two ways. First, a
9c9484bf 468trigger is only called when the attribute is set, as opposed to
efe388d9 469whenever the accessor method is called (for reading or
dab94063 470writing). Second, it is also called when an attribute's value is
471passed to the constructor.
efe388d9 472
473However, triggers are I<not> called when an attribute is populated
474from a C<default> or C<builder>
9c9484bf 475
d67ce58f 476=head2 Attribute types
0b9488c8 477
d4b96efa 478Attributes can be restricted to only accept certain types:
0b9488c8 479
d983b81e 480 has 'first_name' => (
f977e776 481 is => 'ro',
d983b81e 482 isa => 'Str',
483 );
0b9488c8 484
0c39debe 485This says that the C<first_name> attribute must be a string.
0b9488c8 486
487Moose also provides a shortcut for specifying that an attribute only
488accepts objects that do a certain role:
489
d983b81e 490 has 'weapon' => (
491 is => 'rw',
492 does => 'MyApp::Weapon',
493 );
0b9488c8 494
495See the L<Moose::Manual::Types> documentation for a complete
496discussion of Moose's type system.
497
498=head2 Delegation
499
d76a67a8 500An attribute can define methods which simply delegate to its value:
0b9488c8 501
d983b81e 502 has 'hair_color' => (
f977e776 503 is => 'ro',
d983b81e 504 isa => 'Graphics::Color::RGB',
505 handles => { hair_color_hex => 'as_hex_string' },
506 );
0b9488c8 507
d4b96efa 508This adds a new method, C<hair_color_hex>. When someone calls
509C<hair_color_hex>, internally, the object just calls C<<
510$self->hair_color->as_hex_string >>.
0b9488c8 511
0c38f882 512See L<Moose::Manual::Delegation> for documentation on how to set up
0b9488c8 513delegation methods.
514
515=head2 Metaclass and traits
516
517One of Moose's best features is that it can be extended in all sorts
d4b96efa 518of ways through the use of custom metaclasses and metaclass traits.
0b9488c8 519
520When declaring an attribute, you can declare a metaclass or a set of
521traits for the attribute:
522
523 use MooseX::AttributeHelpers;
524
d983b81e 525 has 'mapping' => (
526 metaclass => 'Collection::Hash',
527 is => 'ro',
528 default => sub { {} },
529 );
0b9488c8 530
531In this case, the metaclass C<Collection::Hash> really refers to
0c39debe 532L<MooseX::AttributeHelpers::Collection::Hash>.
0b9488c8 533
534You can also apply one or more traits to an attribute:
535
0b9488c8 536 use MooseX::MetaDescription;
537
d983b81e 538 has 'size' => (
f977e776 539 is => 'ro',
d983b81e 540 traits => ['MooseX::MetaDescription::Meta::Trait'],
541 description => {
542 html_widget => 'text_input',
543 serialize_as => 'element',
544 },
545 );
0b9488c8 546
547The advantage of traits is that you can mix more than one of them
548together easily (in fact, a trait is just a role under the hood).
549
550There are a number of MooseX modules on CPAN which provide useful
551attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
552some examples. You can also write your own metaclasses and traits. See
553the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
554
7261aa9d 555=head1 ATTRIBUTE INHERITANCE
0b9488c8 556
557By default, a child inherits all of its parent class(es)' attributes
d4b96efa 558as-is. However, you can explicitly change some aspects of the
559inherited attribute in the child class.
0b9488c8 560
561The options that can be overridden in a subclass are:
562
563=over 4
564
565=item * default
566
567=item * coerce
568
569=item * required
570
571=item * documentation
572
573=item * lazy
574
575=item * isa
576
577=item * handles
578
579=item * builder
580
581=item * metaclass
582
583=item * traits
584
585=back
586
587To override an attribute, you simply prepend its name with a plus sign
0c39debe 588(C<+>):
0b9488c8 589
590 package LazyPerson;
591
592 use Moose;
593
594 extends 'Person';
595
d983b81e 596 has '+first_name' => (
597 lazy => 1,
598 default => 'Bill',
599 );
0b9488c8 600
601Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
602to C<'Bill'>.
603
604We recommend that you exercise caution when changing the type (C<isa>)
0c38f882 605of an inherited attribute.
0b9488c8 606
7261aa9d 607=head1 MORE ON ATTRIBUTES
608
609Moose attributes are a big topic, and this document glosses over a few
dab94063 610aspects. We recommend that you read the L<Moose::Manual::Delegation>
611and L<Moose::Manual::Types> documents to get a more complete
612understanding of attribute features.
7261aa9d 613
614=head1 A FEW MORE OPTIONS
615
616Moose has lots of attribute options. The ones listed below are
636f25f3 617superseded by some more modern features, but are covered for the sake
7261aa9d 618of completeness.
619
0b9488c8 620=head2 The C<documentation> option
621
622You can provide a piece of documentation as a string for an attribute:
623
d983b81e 624 has 'first_name' => (
625 is => 'rw',
626 documentation => q{The person's first (personal) name},
627 );
0b9488c8 628
629Moose does absolutely nothing with this information other than store
630it.
631
d67ce58f 632=head2 The C<auto_deref> option
0b9488c8 633
634If your attribute is an array reference or hash reference, the
636f25f3 635C<auto_deref> option will make Moose dereference the value when it is
0b9488c8 636returned from the reader method:
637
638 my %map = $object->mapping;
639
640This option only works if your attribute is explicitly typed as an
0c39debe 641C<ArrayRef> or C<HashRef>.
0b9488c8 642
0c39debe 643However, we recommend that you use L<MooseX::AttributeHelpers> for
0b9488c8 644these types of attributes, which gives you much more control over how
645they are accessed and manipulated.
646
647=head2 Initializer
648
649Moose provides an attribute option called C<initializer>. This is
650similar to C<builder>, except that it is I<only> called during object
651construction.
652
0c39debe 653This option is inherited from L<Class::MOP>, but we recommend that you
0b9488c8 654use a C<builder> (which is Moose-only) instead.
655
d4b96efa 656=head1 AUTHOR
657
658Dave Rolsky E<lt>autarch@urth.orgE<gt>
659
660=head1 COPYRIGHT AND LICENSE
661
2840a3b2 662Copyright 2009 by Infinity Interactive, Inc.
d4b96efa 663
664L<http://www.iinteractive.com>
665
666This library is free software; you can redistribute it and/or modify
667it under the same terms as Perl itself.
668
669=cut