I think I've covered all the things that need covering. Still need to
[gitmo/Moose.git] / lib / Moose / Manual / Attributes.pod
CommitLineData
8d38e631 1=pod
2
3=head1 NAME
4
5Moose::Manual::Attribute - Object attributes with Moose
6
7=head1 INTRODUCTION
8
9Attributes are the most feature-rich part of Moose, and also one of
10the most useful. It's easy to imagine a class without roles or method
11modifiers, but almost every class has attributes.
12
13Attributes are properties that every member of a class has. For
14example, we might say that "every Person object has a first name and
15last name. Attributes can be optional, so that we can say "some Person
16objects have a social security number (and some don't)".
17
18At its simplest, an attribute can be thought of slot in hash that can
19be read and set. However, attributes, can also have things like
20default values, laziness, type constraints, delegation and much more.
21
0b9488c8 22=head1 ATTRIBUTE OPTIONS
8d38e631 23
24Use the C<has> function to declare an attribute:
25
26 package Person;
27
28 use Moose;
29
30 has 'first_name' => ( is => 'rw' );
31
32This says that all person objects have an optional "first_name"
33attribute that can be both read and set on the object.
34
35=head2 Read-write Vs Read-only
36
37The code inside the parentheses defines the details of the
38attribute. There are a lot of options you can put here, but in the
39simplest form you just need to include C<is>, which can be either
40C<rw> (read-write) or C<ro> (read-only).
41
42(In fact, you could even omit C<is>, but that leaves you with an
43attribute that has no accessors, which is pointless unless you're
44doing some deep, dark magic).
45
46=head2 Accessor Methods
47
48Each attribute has one or more accessor methods. An accessor lets you
49read and write the value of the attribute for an object.
50
51By default, the accessor method has the same name as the attribute. If
52you declared your attribute as C<ro> then your accessor will be
53read-only. If you declared it read-write, you get a read-write
54accessor. Simple.
55
56So with our Person example above, we now have a single C<first_name>
57accessor that can set or return a person object's first name.
58
59If you want, you can also explicitly specify the method names to be
0b9488c8 60used for reading and writing an attribute's value. This is
8d38e631 61particularly handy when you'd like an attribute to be publically
62readable, but only privately settable. For example:
63
64 has 'weight' =>
65 ( is => 'rw',
66 writer => '_set_weight',
67 );
68
69This might be useful if weight is calculated based on other methods,
70for example every time the C<eat> method is called, we might adjust
71weight. This lets us hide the implementation details of weight
72changes, but still provide the weight value to users of the class.
73
0b9488c8 74Some people might prefer to have distinct methods for reading and
75writing, even when writing is a public method. In I<Perl Best
76Practices>, Damian Conway recommends that reader methods start with
77"get_" and writer methods start with "set_".
8d38e631 78
79We can do exactly that by providing names for both the C<reader> and
80C<writer> methods:
81
82 has 'weight' =>
83 ( is => 'rw',
84 reader => 'get_weight',
85 writer => 'set_weight',
86 );
87
88If you're thinking that doing this over and over would be insanely
89tedious, you're right! Fortunately, Moose provides a powerful
90extension system that lets you do things like override the default
91accessor method conventions. See L<Moose::Manual::MooseX> for more
92details.
93
94=head2 Predicate and Clearer Methods
95
96Moose is able to explicitly distinguish between false or undefined
97values, and an attribute which is not set. If you want to be able to
98access and manipulate these states, you also need to define clearer
99and predicate methods for your attributes.
100
101A predicate method can be used to determine whether or not a given
102attribute is currently set. Note that even if the attribute was
103explicitly set to undef or some other false value, the predicate will
104return true.
105
106The clearer method unsets the attribute. This is I<not> the
107same as setting the value to C<undef>, but you can only distinguish
108between them if you define a predicate method!
109
110Here's some code to illustrate the relationship between an accessor,
111predicate, and clearer method.
112
113 package Person;
114
115 use Moose;
116
117 has 'ssn' =>
118 ( is => 'rw',
119 clearer => 'clear_ssn',
120 predicate => 'has_ssn',
121 );
122
123 ...
124
125 my $person = Person->new();
126 $person->has_ssn; # false
127
128 $person->ssn(undef);
129 $person->ssn; # returns undef
130 $person->has_ssn; # true
131
132 $person->clear_ssn;
133 $person->ssn; # returns undef
134 $person->has_ssn; # false
135
136 $person->ssn('123-45-6789');
137 $person->ssn; # returns '123-45-6789'
138 $person->has_ssn; # true
139
140 my $person2 = Person->new( ssn => '111-22-3333');
141 $person2->has_ssn; # true
142
143Note that by default, Moose does not make a predicate or clearer for
144you. You have to explicitly provide a method name for the ones you
145want.
146
147=head2 Required or Not?
148
149By default, all attributes are optional. That means that they do not
150need to be provided at object construction time. If you want to make
0b9488c8 151an attribute required, simply set the C<required> option to true:
8d38e631 152
153 has 'name' =>
154 ( is => 'rw',
155 required => 1,
156 );
157
158There are a couple caveats worth mentioning in regards to what
159required actually means.
160
161Basically, all it says is that this attribute must be provided to the
162constructor. It does not say anything about its value, so it could be
163C<undef>.
164
165If you define a clearer method on a required attribute, the clearer
166I<will> work. So even though something is defined as required, you can
167remove it after object construction.
168
169So if you do make an attribute required, that probably means that
170providing a clearer doesn't make much sense. In some cases, it might
0b9488c8 171be handy to have a I<private> C<clearer> and C<predicate> for a
172required attribute.
8d38e631 173
174=head2 Default and Builder Methods
175
176Attributes can have default values, and there are several ways to
177specify this.
178
179In the simplest form, you simply provide a non-reference scalar value
0b9488c8 180for the C<default> option:
8d38e631 181
182 has 'size' =>
183 ( is => 'rw',
184 default => 'medium',
185 predicate => 'has_size',
186 );
187
188If the size attribute is not provided to the constructor, then it ends
189up being set to "medium":
190
191 my $person = Person->new();
192 $person->size; # medium
193 $person->has_size; # true
194
0b9488c8 195You can also provide a subroutine reference for C<default>. This
8d38e631 196reference will be called a method on the object.
197
198 has 'size' =>
199 ( is => 'rw',
200 default =>
201 sub { ('small', 'medium', 'large')[ int( rand 3 ) ] },
202 predicate => 'has_size',
203 );
204
205This is dumb example, but it illustrates the point that the subroutine
206will be called for every new object created.
207
208Of course, if it's called during object construction, it may be before
209other attributes have been set. If your default is dependent on other
0b9488c8 210parts of the object's state, you can make the default c<lazy>, which
211is covered in the next section.
8d38e631 212
213If you want to use a reference of any sort as the default value, you
214must return it from a subroutine. This is necessary because otherwise
215Perl would instantiate the reference exactly once, and it would be
216shared by all objects:
217
218 has 'mapping' =>
219 ( is => 'rw',
220 default => {}, # wrong!
221 );
222
223If Moose allowed this then the default mapping attribute could easily
224end up shared across many objects. Instead, wrap it in a subroutine
225reference:
226
227 has 'mapping' =>
228 ( is => 'rw',
229 default => sub { {} }, # right!
230 );
231
232This is a bit awkward, but it's just the way Perl works.
233
234As an alternative to using a subroutine reference, you can instead
0b9488c8 235supply a C<builder> method for your attribute:
8d38e631 236
237 has 'size' =>
238 ( is => 'rw',
239 builder => '_build_size',
240 predicate => 'has_size',
241 );
242
243 sub _build_size {
244 return ('small', 'medium', 'large')[ int( rand 3 ) ];
245 }
246
247This has several advantages. First, it moves a chunk of code to its
248own named method, which improves readability and code
249organization. Second, the C<_build_size> method can be overridden in
250subclasses.
251
0b9488c8 252We strongly recommend that you use a C<builder> instead of a
253C<default> for anything beyond the most trivial default.
8d38e631 254
255=head2 Laziness and lazy_build
256
0b9488c8 257Moose lets you defer attribute population by making an attribute
258C<lazy>:
8d38e631 259
260 has 'size' =>
261 ( is => 'rw',
262 lazy => 1,
263 builder => '_build_size',
264 );
265
0b9488c8 266When the C<lazy> option is true, the attribute is not populated until
267the reader method is called, rather than at object construction
8d38e631 268time. There are several reasons you might choose to do this.
269
270First, if the default value for this attribute depends on some other
0b9488c8 271attributes, then the attribute I<must> be C<lazy>. During object
8d38e631 272construction, default subroutine references are not called in any
273particular order, so you cannot count on other attribute being
274populated at that time.
275
276Second, there's often no reason to spend program time calculating a
0b9488c8 277default before its needed. Making an attribute C<lazy> lets you defer
278the cost until the attribute is needed. If the attribute is I<never>
8d38e631 279needed, you save some CPU time.
280
281We recommend that you make any attribute with a builder or non-trivial
0b9488c8 282default C<lazy> as a matter of course.
8d38e631 283
284To facilitate this, you can simply specify the C<lazy_build> attribute
285option. This bundles up a number of options together:
286
287 has 'size' =>
288 ( is => 'rw',
289 lazy_build => 1,
290 );
291
292This is the same as specifying all of these options:
293
294 has 'size' =>
295 ( is => 'rw',
296 lazy => 1,
297 builder => '_build_size',
298 clearer => 'clear_size',
299 predicate => 'has_size',
300 );
301
302If your attribute name starts with an underscore (_), then the clearer
303and predicate will as well:
304
305 has '_size' =>
306 ( is => 'rw',
307 lazy_build => 1,
308 );
309
0b9488c8 310becomes:
8d38e631 311
312 has '_size' =>
313 ( is => 'rw',
314 lazy => 1,
315 builder => '_build__size',
316 clearer => '_clear_size',
317 predicate => '_has_size',
318 );
319
0b9488c8 320Note the doubled underscore in the builder name. Internally, Moose
321simply prepends the attribute name with "_build_" to come up with the
322builder name.
8d38e631 323
0b9488c8 324If you don't like the names that C<lazy_build> generates, you can
325always provide your own:
326
327 has 'size' =>
328 ( is => 'rw',
329 lazy_build => 1,
330 clearer => '_has_size',
331 );
332
333Options that you explicitly provide are always used in favor of
334Moose's internal defaults.
335
336=head2 Weak References
337
338Moose has built-in support for weak references. If you set the
339C<weak_ref> to a true value for the attribute, then it will call
340C<Scalar::Util::weaken> whenever the attribute is set:
341
342 has 'parent' =>
343 ( is => 'rw',
344 weak_ref => 1,
345 );
346
347 $node->parent($parent_node);
348
349This is very useful when you're building objects that may contain
350circular references.
351
352=head2 Triggers
353
354You can provide a C<trigger> option as a subroutine reference which
355will be called whenever the attribute is set:
356
357 has 'size' =>
358 ( is => 'rw',
359 trigger => \&_size_set,
360 );
361
362 sub _size_set {
363 my ( $self, $size, $meta_attr ) = @_;
364
365 print $self->name, " size is now $size\n";
366 }
367
368The trigger is called as a method, and receives the new value as well
369as the L<Moose::Meta::Attribute> object for the attribute.
370
371=head2 Attribute Types
372
373Attributes can be restriced to only accept certain types:
374
375 has 'first_name' =>
376 ( is => 'rw',
377 isa => 'Str',
378 );
379
380This says that the first_name attribute must be a string.
381
382Moose also provides a shortcut for specifying that an attribute only
383accepts objects that do a certain role:
384
385 has 'weapon' =>
386 ( is => 'rw',
387 does => 'MyApp::Weapon',
388 );
389
390See the L<Moose::Manual::Types> documentation for a complete
391discussion of Moose's type system.
392
393=head2 Delegation
394
395Attributes can define delegations to their values:
396
397 has 'hair_color' =>
398 ( is => 'rw',
399 isa => 'Graphics::Color::RGB',
400 handles => { hair_color_hex => 'as_hex_string' },
401 );
402
403This adds a new method, C<hair_color_hex>. Internally, this just calls
404C<< $self->hair_color->as_hex_string >>.
405
406See L<Moose::Manual::Delegation> for more details on how to set up
407delegation methods.
408
409=head2 Metaclass and traits
410
411One of Moose's best features is that it can be extended in all sorts
412of ways through the use of new metaclasses and metaclass traits.
413
414When declaring an attribute, you can declare a metaclass or a set of
415traits for the attribute:
416
417 use MooseX::AttributeHelpers;
418
419 has 'mapping' =>
420 ( metaclass => 'Collection::Hash',
421 is => 'ro',
422 default => sub { {} },
423 );
424
425In this case, the metaclass C<Collection::Hash> really refers to
426C<MooseX::AttributeHelpers::Collection::Hash>.
427
428You can also apply one or more traits to an attribute:
429
430
431 use MooseX::MetaDescription;
432
433 has 'size' =>
434 ( is => 'rw',
435 traits => [ 'MooseX::MetaDescription::Meta::Trait' ],
436 description => { html_widget => 'text_input',
437 serialize_as => 'element',
438 },
439 );
440
441The advantage of traits is that you can mix more than one of them
442together easily (in fact, a trait is just a role under the hood).
443
444There are a number of MooseX modules on CPAN which provide useful
445attribute metaclasses and traits. See L<Moose::Manual::MooseX> for
446some examples. You can also write your own metaclasses and traits. See
447the "Meta" and "Extending" recipes in L<Moose::Cookbook> for examples.
448
449=head2 Attribute Inheritance
450
451By default, a child inherits all of its parent class(es)' attributes
452as-is. You can explicitly change some aspects of the inherited
453attribute in the child class.
454
455The options that can be overridden in a subclass are:
456
457=over 4
458
459=item * default
460
461=item * coerce
462
463=item * required
464
465=item * documentation
466
467=item * lazy
468
469=item * isa
470
471=item * handles
472
473=item * builder
474
475=item * metaclass
476
477=item * traits
478
479=back
480
481To override an attribute, you simply prepend its name with a plus sign
482(+):
483
484 package LazyPerson;
485
486 use Moose;
487
488 extends 'Person';
489
490 has '+first_name' =>
491 ( lazy => 1,
492 default => 'Bill',
493 );
494
495Now the C<first_name> attribute in C<LazyPerson> is lazy, and defaults
496to C<'Bill'>.
497
498We recommend that you exercise caution when changing the type (C<isa>)
499of an inherited attribute. It's best to only make the new type a
500subtype of the one accepted by the parent.
501
502=head2 The C<documentation> option
503
504You can provide a piece of documentation as a string for an attribute:
505
506 has 'first_name' =>
507 ( is => 'rw',
508 documentation => q{The person's first (personal) name},
509 );
510
511Moose does absolutely nothing with this information other than store
512it.
513
514As an alternative, you might want to look at the
515C<MooseX::MetaDescription> module, which lets you attach a
516"description" to each attribute. This description is a hashref that
517can include meta-information intended for use in other code, as well
518as documentation information.
519
520=head2 The C<auto_deref> Option
521
522If your attribute is an array reference or hash reference, the
523C<auto_deref> option will make Moose de-reference the value when it is
524returned from the reader method:
525
526 my %map = $object->mapping;
527
528This option only works if your attribute is explicitly typed as an
529ArrayRef or HashRef.
530
531However, we recommend that you use C<MooseX::AttributeHelpers> for
532these types of attributes, which gives you much more control over how
533they are accessed and manipulated.
534
535=head2 Initializer
536
537Moose provides an attribute option called C<initializer>. This is
538similar to C<builder>, except that it is I<only> called during object
539construction.
540
541This option is inherited from C<Class::MOP>, but we recommend that you
542use a C<builder> (which is Moose-only) instead.
543
544=head1 MORE ON ATTRIBUTES
545
546Moose attributes are a big topic, and this document glosses over a few
547topics. We recommend that you read the L<Moose::Manual::Delegation>
548and L<Moose::Manual::Types> documents to get a more complete
549understanding of attribute features.