Fix my own suspicious grammar
[gitmo/Moose.git] / lib / Moose / Cookbook / FAQ.pod
1
2 =pod
3
4 =head1 NAME
5
6 Moose::Cookbook::FAQ - Frequently asked questions about Moose
7
8 =head1 FREQUENTLY ASKED QUESTIONS
9
10 =head2 Module Stability
11
12 =head3 Is Moose "production ready"?
13
14 Yes! Many sites with household names are using Moose to build
15 high-traffic services. Countless others are using Moose in
16 production.
17
18 As of this writing, Moose is a dependency of several hundred CPAN
19 modules. L<http://cpants.perl.org/dist/used_by/Moose>
20
21 =head3 Is Moose's API stable?
22
23 Yes. The sugary API, the one 95% of users will interact with, is
24 B<very stable>. Any changes will be B<100% backwards compatible>.
25
26 The meta API is less set in stone. We reserve the right to tweak
27 parts of it to improve efficiency or consistency. This will not be
28 done lightly. We do perform deprecation cycles. We I<really>
29 do not like making ourselves look bad by breaking your code.
30 Submitting test cases is the best way to ensure that your code is not
31 inadvertantly broken by refactoring.
32
33 =head3 I heard Moose is slow, is this true?
34
35 Again, this one is tricky, so Yes I<and> No.
36
37 First let me say that I<nothing> in life is free, and that some
38 Moose features do cost more than others. It is also the
39 policy of Moose to B<only charge you for the features you use>,
40 and to do our absolute best to not place any extra burdens on
41 the execution of your code for features you are not using. Of
42 course using Moose itself does involve some overhead, but it
43 is mostly compile time. At this point we do have some options
44 available for getting the speed you need.
45
46 Currently we have the option of making your classes immutable
47 as a means of boosting speed. This will mean a slightly larger compile
48 time cost, but the runtime speed increase (especially in object
49 construction) is pretty significant. This is not very well
50 documented yet, so please ask on the list or on #moose for more
51 information.
52
53 We are also discussing and experimenting with L<Module::Compile>,
54 and the idea of compiling highly optimized C<.pmc> files. In
55 addition, we have mapped out some core methods as candidates for
56 conversion to XS.
57
58 =head3 When will Moose 1.0 be ready?
59
60 Moose is ready now! Stevan Little declared 0.18, released in March 2007,
61 to be "ready to use".
62
63 =head2 Constructors
64
65 =head3 How do I write custom constructors with Moose?
66
67 Ideally, you should never write your own C<new> method, and should
68 use Moose's other features to handle your specific object construction
69 needs. Here are a few scenarios, and the Moose way to solve them;
70
71 If you need to call initialization code post instance construction,
72 then use the C<BUILD> method. This feature is taken directly from
73 Perl 6. Every C<BUILD> method in your inheritance chain is called
74 (in the correct order) immediately after the instance is constructed.
75 This allows you to ensure that all your superclasses are initialized
76 properly as well. This is the best approach to take (when possible)
77 because it makes subclassing your class much easier.
78
79 If you need to affect the constructor's parameters prior to the
80 instance actually being constructed, you have a number of options.
81
82 To change the parameter processing as a whole, you can use
83 the C<BUILDARGS> method. The default implementation accepts key/value
84 pairs or a hash reference. You can override it to take positional args,
85 or any other format
86
87 To change the handling of individual parameters, there are I<coercions>
88 (See the L<Moose::Cookbook::Basics::Recipe5> for a complete example and
89 explanation of coercions). With coercions it is possible to morph
90 argument values into the correct expected types. This approach is the
91 most flexible and robust, but does have a slightly higher learning
92 curve.
93
94 =head3 How do I make non-Moose constructors work with Moose?
95
96 Usually the correct approach to subclassing a non Moose class is
97 delegation.  Moose makes this easy using the C<handles> keyword,
98 coercions, and C<lazy_build>, so subclassing is often not the
99 ideal route.
100
101 That said, the default Moose constructor is inherited from
102 L<Moose::Object>. When inheriting from a non-Moose class, the
103 inheritance chain to L<Moose::Object> is broken. The simplest way
104 to fix this is to simply explicitly inherit from L<Moose::Object>
105 yourself.
106
107 However, this does not always fix the issue of actually calling the Moose
108 constructor. Fortunately, the modules L<MooseX::NonMoose> and
109 L<MooseX::Alien> aim to make subclassing non-Moose classes easier.
110
111 If neither extension fills your specific needs, you can use
112 L<Class::MOP::Class/new_object>. This low-level constructor accepts the
113 special C<__INSTANCE__> parameter, allowing you to instantiate your Moose
114 attributes:
115
116   package My::HTML::Template;
117   use Moose;
118
119   # explicit inheritance
120   extends 'HTML::Template', 'Moose::Object';
121
122   # explicit constructor
123   sub new {
124       my $class = shift;
125       # call HTML::Template's constructor
126       my $obj = $class->SUPER::new(@_);
127       return $class->meta->new_object(
128           # pass in the constructed object
129           # using the special key __INSTANCE__
130           __INSTANCE__ => $obj,
131           @_, # pass in the normal args
132       );
133   }
134
135 Of course, this only works if both your Moose class and the
136 inherited non-Moose class use the same instance type (typically
137 HASH refs).
138
139 Note that this doesn't call C<BUILDALL> automatically, you must do that
140 yourself.
141
142 Other techniques can be used as well, such as creating the object
143 using C<Moose::Object::new>, but calling the inherited non-Moose
144 class's initialization methods (if available).
145
146 In short, there are several ways to extend non-Moose classes. It is
147 best to evaluate each case based on the class you wish to extend,
148 and the features you wish to employ. As always, both IRC and the
149 mailing list are great ways to get help finding the best approach.
150
151 =head2 Accessors
152
153 =head3 How do I tell Moose to use get/set accessors?
154
155 The easiest way to accomplish this is to use the C<reader> and
156 C<writer> attribute options. Here is some example code:
157
158   has 'bar' => (
159       isa    => 'Baz',
160       reader => 'get_bar',
161       writer => 'set_bar',
162   );
163
164 Moose will still take advantage of type constraints, triggers, etc.
165 when creating these methods.
166
167 If you do not like this much typing, and wish it to be a default for your
168 class, please see L<MooseX::FollowPBP>. This will allow you to write:
169
170   has 'bar' => (
171       isa => 'Baz',
172       is  => 'rw',
173   );
174
175 And have Moose create separate C<get_bar> and C<set_bar> methods
176 instead of a single C<bar> method.
177
178 NOTE: This B<cannot> be set globally in Moose, as that would break
179 other classes which are built with Moose.
180
181 =head3 How can I get Moose to inflate/deflate values in the accessor?
182
183 Well, the first question to ask is if you actually need both inflate
184 and deflate.
185
186 If you only need to inflate, then I suggest using coercions. Here is
187 some basic sample code for inflating a L<DateTime> object:
188
189   subtype 'DateTime'
190       => as 'Object'
191       => where { $_->isa('DateTime') };
192
193   coerce 'DateTime'
194       => from 'Str'
195         => via { DateTime::Format::MySQL->parse_datetime($_) };
196
197   has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
198
199 This creates a custom subtype for L<DateTime> objects, then attaches
200 a coercion to that subtype. The C<timestamp> attribute is then told
201 to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
202 type is given to the C<timestamp> accessor, it will attempt to
203 coerce the value into a C<DateTime> object using the code in found
204 in the C<via> block.
205
206 For a more comprehensive example of using coercions, see the
207 L<Moose::Cookbook::Basics::Recipe5>.
208
209 If you need to deflate your attribute, the current best practice is to
210 add an C<around> modifier to your accessor. Here is some example code:
211
212   # a timestamp which stores as
213   # seconds from the epoch
214   has 'timestamp' => (is => 'rw', isa => 'Int');
215
216   around 'timestamp' => sub {
217       my $next = shift;
218       my ($self, $timestamp) = @_;
219       # assume we get a DateTime object ...
220       $next->($self, $timestamp->epoch);
221   };
222
223 It is also possible to do deflation using coercion, but this tends
224 to get quite complex and require many subtypes. An example of this
225 is outside the scope of this document, ask on #moose or send a mail
226 to the list.
227
228 Still another option is to write a custom attribute metaclass, which
229 is also outside the scope of this document, but I would be happy to
230 explain it on #moose or the mailing list.
231
232 =head2 Method Modifiers
233
234 =head3 How can I affect the values in C<@_> using C<before>?
235
236 You can't, actually: C<before> only runs before the main method,
237 and it cannot easily affect the method's execution.
238
239 You similarly can't use C<after> to affect the return value of a
240 method.
241
242 We limit C<before> and C<after> because this lets you write more
243 concise code. You do not have to worry about passing C<@_> to the
244 original method, or forwarding its response (being careful to preserve
245 context).
246
247 The C<around> method modifier has neither of these limitations.
248
249 =head3 Can I use C<before> to stop execution of a method?
250
251 Yes, but only if you throw an exception. If this is too drastic a
252 measure then I suggest using C<around> instead. The C<around> method
253 modifier is the only modifier which can gracefully prevent execution
254 of the main method. Here is an example:
255
256   around 'baz' => sub {
257       my $next = shift;
258       my ($self, %options) = @_;
259       unless ($options->{bar} eq 'foo') {
260         return 'bar';
261       }
262       $next->($self, %options);
263   };
264
265 By choosing not to call the C<$next> method, you can stop the
266 execution of the main method.
267
268 =head2 Type Constraints
269
270 =head3 How can I have a custom error message for a type constraint?
271
272 Use the C<message> option when building the subtype, like so:
273
274   subtype 'NaturalLessThanTen'
275       => as 'Natural'
276       => where { $_ < 10 }
277       => message { "This number ($_) is not less than ten!" };
278
279 This will be called when a value fails to pass the C<NaturalLessThanTen>
280 constraint check.
281
282 =head3 Can I turn off type constraint checking?
283
284 Not yet, but soon. This option will likely be coming in the next
285 release.
286
287 =head2 Roles
288
289 =head3 How do I get Moose to call BUILD in all my composed roles?
290
291 See L<Moose::Cookbook::WTF> and specifically the B<Why is BUILD
292 not called for my composed roles?> question in the B<Roles> section.
293
294 =head3 What are Traits, and how are they different from Roles?
295
296 In Moose, a trait is almost exactly the same thing as a role, except
297 that traits typically register themselves, which allows you to refer
298 to them by a short name ("Big" vs "MyApp::Role::Big").
299
300 In Moose-speak, a I<Role> is usually composed into a I<class> at
301 compile time, whereas a I<Trait> is usually composed into an instance
302 of a class at runtime to add or modify the behavior of B<just that
303 instance>.
304
305 Outside the context of Moose, traits and roles generally mean exactly the
306 same thing. The original paper called them Traits, however Perl 6 will call
307 them Roles.
308
309 =head1 AUTHOR
310
311 Stevan Little E<lt>stevan@iinteractive.comE<gt>
312
313 =head1 COPYRIGHT AND LICENSE
314
315 Copyright 2006-2009 by Infinity Interactive, Inc.
316
317 L<http://www.iinteractive.com>
318
319 This library is free software; you can redistribute it and/or modify
320 it under the same terms as Perl itself.
321
322 =cut