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