e9aeb6f190e670c59461ccda531ccc87bb15f92f
[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. I have several medium-to-large-ish web applications in 
15 production using Moose, they have been running without 
16 issue now for well over a year. 
17
18 At C<$work> we are re-writing our core offering to use Moose, 
19 so it's continued development is assured. 
20
21 Several other people on #moose either have apps in production 
22 which use Moose, or are in the process of deploying sites 
23 which use Moose. 
24
25 =head3 Is Moose's API stable?
26
27 Yes and No. The external API, the one 90% of users will interact
28 with, is B<very stable> and any changes B<will be 100% backwards 
29 compatible>. The introspection API is I<mostly> stable; I still 
30 reserve the right to tweak that if needed, but I will do my 
31 absolute best to maintain backwards compatibility here as well.
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 It is right now, I declared 0.18 to be "ready to use".
61
62 =head2 Constructors
63
64 =head3 How do I write custom constructors with Moose?
65
66 Ideally, you should never write your own C<new> method, and should
67 use Moose's other features to handle your specific object construction
68 needs. Here are a few scenarios, and the Moose way to solve them;
69
70 If you need to call initialization code post instance construction, 
71 then use the C<BUILD> method. This feature is taken directly from 
72 Perl 6. Every C<BUILD> method in your inheritance chain is called 
73 (in the correct order) immediately after the instance is constructed. 
74 This allows you to ensure that all your superclasses are initialized 
75 properly as well. This is the best approach to take (when possible)
76 because it makes sub classing your class much easier.
77
78 If you need to affect the constructor's parameters prior to the 
79 instance actually being constructed, you have a number of options.
80
81 To change the parameter processing as a whole, you can use
82 the C<BUILDARGS> method. The default implementation accepts key/value
83 pairs or a hash reference. You can override it to take positional args,
84 or any other format
85
86 To change the handling of individual parameters, there are I<coercions>
87 (See the L<Moose::Cookbook::Recipe5> for a complete example and
88 explaination of coercions). With coercions it is possible to morph
89 argument values into the correct expected types. This approach is the
90 most flexible and robust, but does have a slightly higher learning
91 curve.
92
93 =head3 How do I make non-Moose constructors work with Moose? 
94
95 Moose provides its own constructor, but it does it by making all 
96 Moose-based classes inherit from L<Moose::Object>. When inheriting
97 from a non-Moose class, the inheritance chain to L<Moose::Object> 
98 is broken. The simplest way to fix this is to simply explicitly 
99 inherit from L<Moose::Object> yourself. However, this does not 
100 always fix the issue of a constructor. Here is a basic example of 
101 how this can be worked around:
102
103   package My::HTML::Template;
104   use Moose;
105   
106   # explicit inheritance 
107   extends 'HTML::Template', 'Moose::Object';
108   
109   # explicit constructor
110   sub new {
111       my $class = shift;
112       # call HTML::Template's constructor
113       my $obj = $class->SUPER::new(@_);
114       return $class->meta->new_object(
115           # pass in the constructed object
116           # using the special key __INSTANCE__
117           __INSTANCE__ => $obj, @_
118       );
119   }
120
121 Of course, this only works if both your Moose class and the 
122 inherited non-Moose class use the same instance type (typically 
123 HASH refs). 
124
125 Other techniques can be used as well, such as creating the object 
126 using C<Moose::Object::new>, but calling the inherited non-Moose 
127 class's initialization methods (if available). 
128
129 It is also entirely possible to just rely on HASH autovivification
130 to create the slots needed for Moose based attributes, although this
131 does restrict use of construction time attribute features somewhat.
132
133 In short, there are several ways to go about this, it is best to 
134 evaluate each case based on the class you wish to extend, and the 
135 features you wish to employ. As always, both IRC and the mailing 
136 list are great ways to get help finding the best approach.
137
138 =head2 Accessors
139
140 =head3 How do I tell Moose to use get/set accessors?
141
142 The easiest way to accomplish this is to use the C<reader> and 
143 C<writer> attribute options. Here is some example code:
144
145   has 'bar' => (
146       isa    => 'Baz',
147       reader => 'get_bar', 
148       writer => 'set_bar',
149   );
150
151 Moose will still take advantage of type constraints, triggers, etc. 
152 when creating these methods. 
153
154 If you do not like this much typing, and wish it to be a default for
155 your class, please see L<Moose::Policy>, and more specifically
156 L<Moose::Policy::FollowPBP>. This will allow you to write:
157
158   has 'bar' => (
159       isa => 'Baz',
160       is  => 'rw',
161   );
162
163 And have Moose create seperate C<get_bar> and C<set_bar> methods
164 instead of a single C<bar> method.
165
166 NOTE: This B<cannot> be set globally in Moose, as that would break 
167 other classes which are built with Moose.
168
169 =head3 How can I get Moose to inflate/deflate values in the accessor?
170
171 Well, the first question to ask is if you actually need both inflate 
172 and deflate.
173
174 If you only need to inflate, then I suggest using coercions. Here is 
175 some basic sample code for inflating a L<DateTime> object:
176
177   subtype 'DateTime'
178       => as 'Object'
179       => where { $_->isa('DateTime') };
180       
181   coerce 'DateTime'
182       => from 'Str'
183         => via { DateTime::Format::MySQL->parse_datetime($_) };
184         
185   has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
186
187 This creates a custom subtype for L<DateTime> objects, then attaches 
188 a coercion to that subtype. The C<timestamp> attribute is then told 
189 to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
190 type is given to the C<timestamp> accessor, it will attempt to 
191 coerce the value into a C<DateTime> object using the code in found 
192 in the C<via> block. 
193
194 For a more comprehensive example of using coercions, see the
195 L<Moose::Cookbook::Recipe5>.
196
197 If you need to deflate your attribute, the current best practice is to 
198 add an C<around> modifier to your accessor. Here is some example code:
199
200   # a timestamp which stores as 
201   # seconds from the epoch
202   has 'timestamp' => (is => 'rw', isa => 'Int');
203   
204   around 'timestamp' => sub {
205       my $next = shift;
206       my ($self, $timestamp) = @_;
207       # assume we get a DateTime object ...
208       $next->($self, $timestamp->epoch);
209   };
210
211 It is also possible to do deflation using coercion, but this tends 
212 to get quite complex and require many subtypes. An example of this 
213 is outside the scope of this document, ask on #moose or send a mail 
214 to the list.
215
216 Still another option is to write a custom attribute metaclass, which 
217 is also outside the scope of this document, but I would be happy to 
218 explain it on #moose or the mailing list.
219
220 =head2 Method Modifiers
221
222 =head3 How can I affect the values in C<@_> using C<before>?
223
224 You can't, actually: C<before> only runs before the main method, 
225 and it cannot easily affect the method's execution. What you want is 
226 an C<around> method. 
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 I 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       $next->($self, %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 =head2 Type Constraints
248
249 =head3 How can I have a custom error message for a type constraint?
250
251 Use the C<message> option when building the subtype, like so:
252
253   subtype 'NaturalLessThanTen' 
254       => as 'Natural'
255       => where { $_ < 10 }
256       => message { "This number ($_) is not less than ten!" };
257
258 This will be called when a value fails to pass the C<NaturalLessThanTen>
259 constraint check. 
260
261 =head3 Can I turn off type constraint checking?
262
263 Not yet, but soon. This option will likely be coming in the next 
264 release.
265
266 =head2 Roles
267
268 =head3 How do I get Moose to call BUILD in all my composed roles?
269
270 See L<Moose::Cookbook::WTF> and specifically the B<How come BUILD 
271 is not called for my composed roles?> question in the B<Roles> section.
272
273 =head1 AUTHOR
274
275 Stevan Little E<lt>stevan@iinteractive.comE<gt>
276
277 =head1 COPYRIGHT AND LICENSE
278
279 Copyright 2006-2008 by Infinity Interactive, Inc.
280
281 L<http://www.iinteractive.com>
282
283 This library is free software; you can redistribute it and/or modify
284 it under the same terms as Perl itself.
285
286 =cut