Checking in the first chunk of the Attributes manual section
[gitmo/Moose.git] / lib / Moose / Manual / Attributes.pod
1 =pod
2
3 =head1 NAME
4
5 Moose::Manual::Attribute - Object attributes with Moose
6
7 =head1 INTRODUCTION
8
9 Attributes are the most feature-rich part of Moose, and also one of
10 the most useful. It's easy to imagine a class without roles or method
11 modifiers, but almost every class has attributes.
12
13 Attributes are properties that every member of a class has. For
14 example, we might say that "every Person object has a first name and
15 last name. Attributes can be optional, so that we can say "some Person
16 objects have a social security number (and some don't)".
17
18 At its simplest, an attribute can be thought of slot in hash that can
19 be read and set. However, attributes, can also have things like
20 default values, laziness, type constraints, delegation and much more.
21
22 =head1 ATTRIBUTE 101
23
24 Use the C<has> function to declare an attribute:
25
26   package Person;
27
28   use Moose;
29
30   has 'first_name' => ( is => 'rw' );
31
32 This says that all person objects have an optional "first_name"
33 attribute that can be both read and set on the object.
34
35 =head2 Read-write Vs Read-only
36
37 The code inside the parentheses defines the details of the
38 attribute. There are a lot of options you can put here, but in the
39 simplest form you just need to include C<is>, which can be either
40 C<rw> (read-write) or C<ro> (read-only).
41
42 (In fact, you could even omit C<is>, but that leaves you with an
43 attribute that has no accessors, which is pointless unless you're
44 doing some deep, dark magic).
45
46 =head2 Accessor Methods
47
48 Each attribute has one or more accessor methods. An accessor lets you
49 read and write the value of the attribute for an object.
50
51 By default, the accessor method has the same name as the attribute. If
52 you declared your attribute as C<ro> then your accessor will be
53 read-only. If you declared it read-write, you get a read-write
54 accessor. Simple.
55
56 So with our Person example above, we now have a single C<first_name>
57 accessor that can set or return a person object's first name.
58
59 If you want, you can also explicitly specify the method names to be
60 used for getting and setting an attribute's value. This is
61 particularly handy when you'd like an attribute to be publically
62 readable, but only privately settable. For example:
63
64   has 'weight' =>
65       ( is     => 'rw',
66         writer => '_set_weight',
67       );
68
69 This might be useful if weight is calculated based on other methods,
70 for example every time the C<eat> method is called, we might adjust
71 weight. This lets us hide the implementation details of weight
72 changes, but still provide the weight value to users of the class.
73
74 Some people might prefer to have distinct methods for getting and
75 setting, even when setting is a public method. In I<Perl Best
76 Practices>, Damian Conway recommends that getter methods start with
77 "get_" and setter methods start with "set_".
78
79 We can do exactly that by providing names for both the C<reader> and
80 C<writer> methods:
81
82   has 'weight' =>
83       ( is     => 'rw',
84         reader => 'get_weight',
85         writer => 'set_weight',
86       );
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
96 Moose is able to explicitly distinguish between false or undefined
97 values, and an attribute which is not set. If you want to be able to
98 access and manipulate these states, you also need to define clearer
99 and predicate methods for your attributes.
100
101 A predicate method can be used to determine whether or not a given
102 attribute is currently set. Note that even if the attribute was
103 explicitly set to undef or some other false value, the predicate will
104 return true.
105
106 The clearer method unsets the attribute. This is I<not> the
107 same as setting the value to C<undef>, but you can only distinguish
108 between them if you define a predicate method!
109
110 Here's some code to illustrate the relationship between an accessor,
111 predicate, 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
143 Note that by default, Moose does not make a predicate or clearer for
144 you. You have to explicitly provide a method name for the ones you
145 want.
146
147 =head2 Required or Not?
148
149 By default, all attributes are optional. That means that they do not
150 need to be provided at object construction time. If you want to make
151 an attribute required, simply set the required option to true:
152
153   has 'name' =>
154       ( is       => 'rw',
155         required => 1,
156       );
157
158 There are a couple caveats worth mentioning in regards to what
159 required actually means.
160
161 Basically, all it says is that this attribute must be provided to the
162 constructor. It does not say anything about its value, so it could be
163 C<undef>.
164
165 If you define a clearer method on a required attribute, the clearer
166 I<will> work. So even though something is defined as required, you can
167 remove it after object construction.
168
169 So if you do make an attribute required, that probably means that
170 providing a clearer doesn't make much sense. In some cases, it might
171 be handy to have a I<private> clearer and predicate for a required
172 attribute.
173
174 =head2 Default and Builder Methods
175
176 Attributes can have default values, and there are several ways to
177 specify this.
178
179 In the simplest form, you simply provide a non-reference scalar value
180 for the "default" option:
181
182   has 'size' =>
183       ( is        => 'rw',
184         default   => 'medium',
185         predicate => 'has_size',
186       );
187
188 If the size attribute is not provided to the constructor, then it ends
189 up being set to "medium":
190
191   my $person = Person->new();
192   $person->size; # medium
193   $person->has_size; # true
194
195 You can also provide a subroutine reference for default. This
196 reference 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
205 This is dumb example, but it illustrates the point that the subroutine
206 will be called for every new object created.
207
208 Of course, if it's called during object construction, it may be before
209 other attributes have been set. If your default is dependent on other
210 parts of the object's state, you can make the default lazy, which is
211 covered in the next section.
212
213 If you want to use a reference of any sort as the default value, you
214 must return it from a subroutine. This is necessary because otherwise
215 Perl would instantiate the reference exactly once, and it would be
216 shared by all objects:
217
218   has 'mapping' =>
219       ( is      => 'rw',
220         default => {}, # wrong!
221       );
222
223 If Moose allowed this then the default mapping attribute could easily
224 end up shared across many objects. Instead, wrap it in a subroutine
225 reference:
226
227   has 'mapping' =>
228       ( is      => 'rw',
229         default => sub { {} }, # right!
230       );
231
232 This is a bit awkward, but it's just the way Perl works.
233
234 As an alternative to using a subroutine reference, you can instead
235 supply a builder method for your attribute:
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
247 This has several advantages. First, it moves a chunk of code to its
248 own named method, which improves readability and code
249 organization. Second, the C<_build_size> method can be overridden in
250 subclasses.
251
252 We strongly recommend that you use a builder instead of a default for
253 anything beyond the most trivial default.
254
255 =head2 Laziness and lazy_build
256
257 Moose lets you defer attribute population by making an attribute lazy:
258
259   has 'size' =>
260       ( is        => 'rw',
261         lazy      => 1,
262         builder   => '_build_size',
263       );
264
265 When the lazy option is true, the attribute is not populated until the
266 reader method is called, rather than at object construction
267 time. There are several reasons you might choose to do this.
268
269 First, if the default value for this attribute depends on some other
270 attributes, then the attribute I<must> be lazy. During object
271 construction, default subroutine references are not called in any
272 particular order, so you cannot count on other attribute being
273 populated at that time.
274
275 Second, there's often no reason to spend program time calculating a
276 default before its needed. Making an attribute lazy lets you defer the
277 cost until the attribute is needed. If the attribute is I<never>
278 needed, you save some CPU time.
279
280 We recommend that you make any attribute with a builder or non-trivial
281 default lazy as a matter of course.
282
283 To facilitate this, you can simply specify the C<lazy_build> attribute
284 option. This bundles up a number of options together:
285
286   has 'size' =>
287       ( is         => 'rw',
288         lazy_build => 1,
289       );
290
291 This is the same as specifying all of these options:
292
293   has 'size' =>
294       ( is        => 'rw',
295         lazy      => 1,
296         builder   => '_build_size',
297         clearer   => 'clear_size',
298         predicate => 'has_size',
299       );
300
301 If your attribute name starts with an underscore (_), then the clearer
302 and predicate will as well:
303
304   has '_size' =>
305       ( is         => 'rw',
306         lazy_build => 1,
307       );
308
309 becomes ...
310
311   has '_size' =>
312       ( is        => 'rw',
313         lazy      => 1,
314         builder   => '_build__size',
315         clearer   => '_clear_size',
316         predicate => '_has_size',
317       );
318
319 Note the doubled underscore in the builder name. The lazy_build simply
320 prepends the attribute name with "_build_" to come up with the builder
321 name.
322
323 =head2 Private Attributes