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