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