ad94e09f426bcffd1c5dd241bdff1afbda187507
[gitmo/Moose.git] / lib / Moose / Manual / FAQ.pod
1 package Moose::Manual::FAQ;
2
3 # ABSTRACT: Frequently asked questions about Moose
4
5 __END__
6
7
8 =pod
9
10 =head1 FREQUENTLY ASKED QUESTIONS
11
12 =head2 Module Stability
13
14 =head3 Is Moose "production ready"?
15
16 Yes! Many sites with household names are using Moose to build
17 high-traffic services. Countless others are using Moose in production.
18 See L<http://www.iinteractive.com/moose/about.html#organizations> for
19 a partial list.
20
21 As of this writing, Moose is a dependency of several hundred CPAN
22 modules. L<http://cpants.perl.org/dist/used_by/Moose>
23
24 =head3 Is Moose's API stable?
25
26 Yes. The sugary API, the one 95% of users will interact with, is
27 B<very stable>. Any changes will be B<100% backwards compatible>.
28
29 The meta API is less set in stone. We reserve the right to tweak
30 parts of it to improve efficiency or consistency. This will not be
31 done lightly. We do perform deprecation cycles. We I<really>
32 do not like making ourselves look bad by breaking your code.
33 Submitting test cases is the best way to ensure that your code is not
34 inadvertently broken by refactoring.
35
36 =head3 I heard Moose is slow, is this true?
37
38 Again, this one is tricky, so Yes I<and> No.
39
40 Firstly, I<nothing> in life is free, and some Moose features do cost
41 more than others. It is also the policy of Moose to B<only charge you
42 for the features you use>, and to do our absolute best to not place
43 any extra burdens on the execution of your code for features you are
44 not using. Of course using Moose itself does involve some overhead,
45 but it is mostly compile time. At this point we do have some options
46 available for getting the speed you need.
47
48 Currently we provide the option of making your classes immutable as a
49 means of boosting speed. This will mean a slightly larger compile time
50 cost, but the runtime speed increase (especially in object
51 construction) is pretty significant. This can be done with the
52 following code:
53
54   MyClass->meta->make_immutable();
55
56 =head3 When will Moose 1.0 be ready?
57
58 Moose is ready now! Stevan Little declared 0.18, released in March
59 2007, to be "ready to use".
60
61 =head2 Constructors
62
63 =head3 How do I write custom constructors with Moose?
64
65 Ideally, you should never write your own C<new> method, and should use
66 Moose's other features to handle your specific object construction
67 needs. Here are a few scenarios, and the Moose way to solve them;
68
69 If you need to call initialization code post instance construction,
70 then use the C<BUILD> method. This feature is taken directly from Perl
71 6. Every C<BUILD> method in your inheritance chain is called (in the
72 correct order) immediately after the instance is constructed.  This
73 allows you to ensure that all your superclasses are initialized
74 properly as well. This is the best approach to take (when possible)
75 because it makes subclassing your class much easier.
76
77 If you need to affect the constructor's parameters prior to the
78 instance actually being constructed, you have a number of options.
79
80 To change the parameter processing as a whole, you can use the
81 C<BUILDARGS> method. The default implementation accepts key/value
82 pairs or a hash reference. You can override it to take positional
83 args, or any other format
84
85 To change the handling of individual parameters, there are
86 I<coercions> (See the L<Moose::Cookbook::Basics::Recipe5> for a
87 complete example and explanation of coercions). With coercions it is
88 possible to morph argument values into the correct expected
89 types. This approach is the most flexible and robust, but does have a
90 slightly higher learning curve.
91
92 =head3 How do I make non-Moose constructors work with Moose?
93
94 Usually the correct approach to subclassing a non-Moose class is
95 delegation.  Moose makes this easy using the C<handles> keyword,
96 coercions, and C<lazy_build>, so subclassing is often not the ideal
97 route.
98
99 That said, if you really need to inherit from a non-Moose class, see
100 L<Moose::Cookbook::Basics::Recipe11> for an example of how to do it,
101 or take a look at L<Moose::Manual::MooseX/"MooseX::NonMoose">.
102
103 =head2 Accessors
104
105 =head3 How do I tell Moose to use get/set accessors?
106
107 The easiest way to accomplish this is to use the C<reader> and
108 C<writer> attribute options:
109
110   has 'bar' => (
111       isa    => 'Baz',
112       reader => 'get_bar',
113       writer => 'set_bar',
114   );
115
116 Moose will still take advantage of type constraints, triggers, etc.
117 when creating these methods.
118
119 If you do not like this much typing, and wish it to be a default for
120 your classes, please see L<MooseX::FollowPBP>. This extension will
121 allow you to write:
122
123   has 'bar' => (
124       isa => 'Baz',
125       is  => 'rw',
126   );
127
128 Moose will create separate C<get_bar> and C<set_bar> methods instead
129 of a single C<bar> method.
130
131 If you like C<bar> and C<set_bar>, see
132 L<MooseX::SemiAffordanceAccessor>.
133
134 NOTE: This B<cannot> be set globally in Moose, as that would break
135 other classes which are built with Moose. You can still save on typing
136 by defining a new L<MyApp::Moose> that exports Moose's sugar and then
137 turns on L<MooseX::FollowPBP>. See
138 L<Moose::Cookbook::Extending::Recipe4>.
139
140 =head3 How can I inflate/deflate values in accessors?
141
142 Well, the first question to ask is if you actually need both inflate
143 and deflate.
144
145 If you only need to inflate, then we suggest using coercions. Here is
146 some basic sample code for inflating a L<DateTime> object:
147
148   class_type 'DateTime';
149
150   coerce 'DateTime'
151       => from 'Str'
152       => via { DateTime::Format::MySQL->parse_datetime($_) };
153
154   has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
155
156 This creates a custom type for L<DateTime> objects, then attaches
157 a coercion to that type. The C<timestamp> attribute is then told
158 to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
159 type is given to the C<timestamp> accessor, it will attempt to
160 coerce the value into a C<DateTime> object using the code in found
161 in the C<via> block.
162
163 For a more comprehensive example of using coercions, see the
164 L<Moose::Cookbook::Basics::Recipe5>.
165
166 If you need to deflate your attribute's value, the current best
167 practice is to add an C<around> modifier to your accessor:
168
169   # a timestamp which stores as
170   # seconds from the epoch
171   has 'timestamp' => (is => 'rw', isa => 'Int');
172
173   around 'timestamp' => sub {
174       my $next = shift;
175       my $self = shift;
176
177       return $self->$next unless @_;
178
179       # assume we get a DateTime object ...
180       my $timestamp = shift;
181       return $self->$next( $timestamp->epoch );
182   };
183
184 It is also possible to do deflation using coercion, but this tends to
185 get quite complex and require many subtypes. An example of this is
186 outside the scope of this document, ask on #moose or send a mail to
187 the list.
188
189 Still another option is to write a custom attribute metaclass, which
190 is also outside the scope of this document, but we would be happy to
191 explain it on #moose or the mailing list.
192
193 =head3 I created an attribute, where are my accessors?
194
195 Accessors are B<not> created implicitly, you B<must> ask Moose to
196 create them for you. My guess is that you have this:
197
198   has 'foo' => (isa => 'Bar');
199
200 when what you really want to say is:
201
202   has 'foo' => (isa => 'Bar', is => 'rw');
203
204 The reason this is so is because it is a perfectly valid use case to
205 I<not> have an accessor. The simplest one is that you want to write
206 your own. If Moose created one automatically, then because of the
207 order in which classes are constructed, Moose would overwrite your
208 custom accessor. You wouldn't want that would you?
209
210 =head2 Method Modifiers
211
212 =head3 How can I affect the values in C<@_> using C<before>?
213
214 You can't, actually: C<before> only runs before the main method, and
215 it cannot easily affect the method's execution.
216
217 You similarly can't use C<after> to affect the return value of a
218 method.
219
220 We limit C<before> and C<after> because this lets you write more
221 concise code. You do not have to worry about passing C<@_> to the
222 original method, or forwarding its return value (being careful to
223 preserve context).
224
225 The C<around> method modifier has neither of these limitations, but is
226 a little more verbose.
227
228 =head3 Can I use C<before> to stop execution of a method?
229
230 Yes, but only if you throw an exception. If this is too drastic a
231 measure then we suggest using C<around> instead. The C<around> method
232 modifier is the only modifier which can gracefully prevent execution
233 of the main method. Here is an example:
234
235     around 'baz' => sub {
236         my $next = shift;
237         my ($self, %options) = @_;
238         unless ($options->{bar} eq 'foo') {
239             return 'bar';
240         }
241         $self->$next(%options);
242     };
243
244 By choosing not to call the C<$next> method, you can stop the
245 execution of the main method.
246
247 =head3 Why can't I see return values in an C<after> modifier?
248
249 As with the C<before> modifier, the C<after> modifier is simply called
250 I<after> the main method. It is passed the original contents of C<@_>
251 and B<not> the return values of the main method.
252
253 Again, the arguments are too lengthy as to why this has to be. And as
254 with C<before> I recommend using an C<around> modifier instead.  Here
255 is some sample code:
256
257   around 'foo' => sub {
258       my $next = shift;
259       my ($self, @args) = @_;
260       my @rv = $next->($self, @args);
261       # do something silly with the return values
262       return reverse @rv;
263   };
264
265 =head2 Type Constraints
266
267 =head3 How can I provide a custom error message for a type constraint?
268
269 Use the C<message> option when building the subtype:
270
271   subtype 'NaturalLessThanTen'
272       => as 'Natural'
273       => where { $_ < 10 }
274       => message { "This number ($_) is not less than ten!" };
275
276 This C<message> block will be called when a value fails to pass the
277 C<NaturalLessThanTen> constraint check.
278
279 =head3 Can I turn off type constraint checking?
280
281 Not yet. This option may come in a future release.
282
283 =head3 My coercions stopped working with recent Moose, why did you break it?
284
285 Moose 0.76 fixed a case where Coercions were being applied even if the original constraint passed. This has caused some edge cases to fail where people were doing something like
286
287     subtype Address => as 'Str';
288     coerce Address => from Str => via { get_address($_) };
289
290 Which is not what they intended. The Type Constraint C<Address> is too loose in this case, it is saying that all Strings are Addresses, which is obviously not the case. The solution is to provide a where clause that properly restricts the Type Constraint.
291
292     subtype Address => as Str => where { looks_like_address($_) };
293
294 This will allow the coercion to apply only to strings that fail to look like an Address.
295
296 =head2 Roles
297
298 =head3 Why is BUILD not called for my composed roles?
299
300 C<BUILD> is never called in composed roles. The primary reason is that
301 roles are B<not> order sensitive. Roles are composed in such a way
302 that the order of composition does not matter (for information on the
303 deeper theory of this read the original traits papers here
304 L<http://www.iam.unibe.ch/~scg/Research/Traits/>).
305
306 Because roles are essentially unordered, it would be impossible to
307 determine the order in which to execute the C<BUILD> methods.
308
309 As for alternate solutions, there are a couple.
310
311 =over 4
312
313 =item *
314
315 Using a combination of lazy and default in your attributes to defer
316 initialization (see the Binary Tree example in the cookbook for a good
317 example of lazy/default usage L<Moose::Cookbook::Basics::Recipe3>)
318
319 =item *
320
321 Use attribute triggers, which fire after an attribute is set, to
322 facilitate initialization. These are described in the L<Moose> docs,
323 and examples can be found in the test suite.
324
325 =back
326
327 In general, roles should not I<require> initialization; they should
328 either provide sane defaults or should be documented as needing
329 specific initialization. One such way to "document" this is to have a
330 separate attribute initializer which is required for the role. Here is
331 an example of how to do this:
332
333   package My::Role;
334   use Moose::Role;
335
336   has 'height' => (
337       is      => 'rw',
338       isa     => 'Int',
339       lazy    => 1,
340       default => sub {
341           my $self = shift;
342           $self->init_height;
343       }
344   );
345
346   requires 'init_height';
347
348 In this example, the role will not compose successfully unless the
349 class provides a C<init_height> method.
350
351 If none of those solutions work, then it is possible that a role is
352 not the best tool for the job, and you really should be using
353 classes. Or, at the very least, you should reduce the amount of
354 functionality in your role so that it does not require initialization.
355
356 =head3 What are Traits, and how are they different from Roles?
357
358 In Moose, a trait is almost exactly the same thing as a role, except
359 that traits typically register themselves, which allows you to refer
360 to them by a short name ("Big" vs "MyApp::Role::Big").
361
362 In Moose-speak, a I<Role> is usually composed into a I<class> at
363 compile time, whereas a I<Trait> is usually composed into an instance
364 of a class at runtime to add or modify the behavior of B<just that
365 instance>.
366
367 Outside the context of Moose, traits and roles generally mean exactly
368 the same thing. The original paper called them Traits, however Perl 6
369 will call them Roles.
370
371 =head2 Moose and Subroutine Attributes
372
373 =head3 Why don't subroutine attributes I inherited from a superclass work?
374
375 Currently when you subclass a module, this is done at runtime with the
376 C<extends> keyword but attributes are checked at compile time by
377 Perl. To make attributes work, you must place C<extends> in a C<BEGIN>
378 block so that the attribute handlers will be available at compile time
379 like this:
380
381   BEGIN { extends qw/Foo/ }
382
383 Note that we're talking about Perl's subroutine attributes here, not
384 Moose attributes:
385
386   sub foo : Bar(27) { ... }
387
388 =cut