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