test with Test::Deep::eq_deeply
[gitmo/Moose.git] / lib / Moose / Cookbook / FAQ.pod
CommitLineData
e67a0fca 1
2=pod
3
4=head1 NAME
5
6Moose::Cookbook::FAQ - Frequenty asked questions about Moose
7
8=head1 FREQUENTLY ASKED QUESTIONS
9
2a0f3bd3 10=head2 Module Stability
11
12=head3 Is Moose "production ready"?
13
734d1752 14Yes. I have two medium-to-large-ish web applications in
15production using Moose, they have been running without
16issue now for almost a year.
17
18At $work we are re-writing our core offering to use Moose,
19so it's continued development is assured.
20
21Several other people on #moose either have apps in production
22which use Moose, or are in the process of deploying sites
23which use Moose.
2a0f3bd3 24
25=head3 Is Moose's API stable?
26
27Yes and No. The external API, the one 90% of users will interact
28with, is B<very stable> and any changes B<will be 100% backwards
29compatible>. The introspection API is I<mostly> stable, I still
30reserve the right to tweak that if needed, but I will do my
31absolute best to maintain backwards comptability here as well.
32
734d1752 33=head3 I heard Moose is slow, is this true?
2a0f3bd3 34
35Again, this one is tricky, so Yes I<and> No.
36
37First let me say that I<nothing> in life is free, and that some
38Moose features do cost more than others. It is also the
39policy of Moose to B<only charge you for the features you use>,
40and to do our absolute best to not place any extra burdens on
41the execution of your code for features you are not using.
42
43Next, I will point out again that we are still in the "early
44adopter" phase, so speed it not that important yet. We are
45actually optimizing for "theoretical correctness" first, and
46we will optimize for speed later. It has been our experience
47that taking this approach allows for greater optimization
48capacity.
49
734d1752 50Currently we have the option of making your classes immutable
51as a means of boosting speed. This will mean a larger compile
52time cost, but the runtime speed increase (especially in object
53construction) is pretty signifigant.
2a0f3bd3 54
734d1752 55This is not all either, we are also discussing and experimenting
56with L<Module::Compile>, and the idea of compiling highly
57optimized C<.pmc> files. And we have also mapped out some core
58methods as canidates for conversion to XS.
2a0f3bd3 59
60=head3 When will Moose be 1.0 ready?
61
734d1752 62I had originally said it would be end of 2006, but various bits
63of $work kept me too busy. At this point, I think we are getting
64pretty close and I will likely declare 1.0 within the next few
65releases.
2a0f3bd3 66
734d1752 67When will that be? Hard to say really, but honestly, it is ready
68to use now, the difference between now and 1.0 will be pretty
69minimal.
2a0f3bd3 70
e67a0fca 71=head2 Constructors
72
73=head3 How do I write custom constructors with Moose?
74
75Ideally, you should never write your own C<new> method, and should
76use Moose's other features to handle your specific object construction
77needs. Here are a few scenarios, and the Moose way to solve them;
78
79If you need to call initializtion code post instance construction,
80then use the C<BUILD> method. This feature is taken directly from
81Perl 6. Every C<BUILD> method in your inheritence chain is called
82(in the correct order) immediately after the instance is constructed.
83This allows you to ensure that all your superclasses are initialized
84properly as well. This is the best approach to take (when possible)
85because it makes subclassing your class much easier.
86
87If you need to affect the constructor's parameters prior to the
88instance actually being constructed, you have a number of options.
89
90First, there are I<coercions> (See the L<Moose::Cookbook::Recipe5>
91for a complete example and explaination of coercions). With
92coercions it is possible to morph argument values into the correct
93expected types. This approach is the most flexible and robust, but
94does have a slightly higher learning curve.
95
96Second, using an C<around> method modifier on C<new> can be an
97effective way to affect the contents of C<@_> prior to letting
98Moose deal with it. This carries with it the extra burden for
99your subclasses, in that they have to be sure to explicitly
100call your C<new> and/or work around your C<new> to get to the
101version from L<Moose::Object>.
102
103The last approach is to use the standard Perl technique of calling
104the C<SUPER::new> within your own custom version of C<new>. This
105of course brings with it all the issues of the C<around> solution
106along with any issues C<SUPER::> might add as well.
107
108In short, try to use C<BUILD> and coercions, they are your best
109bets.
110
111=head3 How do I make non-Moose constuctors work with Moose?
112
113Moose provides it's own constructor, but it does it by making all
114Moose-based classes inherit from L<Moose::Object>. When inheriting
115from a non-Moose class, the inheritence chain to L<Moose::Object>
116is broken. The simplest way to fix this is to simply explicitly
117inherit from L<Moose::Object> yourself. However, this does not
118always fix the issue of a constructor. Here is a basic example of
119how this can be worked around:
120
121 package My::HTML::Template;
122 use Moose;
123
124 # explict inheritence
125 extends 'HTML::Template', 'Moose::Object';
126
127 # explicit constructor
128 sub new {
129 my $class = shift;
130 # call HTML::Template's constructor
131 my $obj = $class->SUPER::new(@_);
132 return $class->meta->new_object(
133 # pass in the constructed object
134 # using the special key __INSTANCE__
135 __INSTANCE__ => $obj, @_
136 );
137 }
138
139Of course this only works if both your Moose class, and the
140inherited non-Moose class use the same instance type (typically
141HASH refs).
142
143Other techniques can be used as well, such as creating the object
144using C<Moose::Object::new>, but calling the inherited non-Moose
145class's initializtion methods (if available).
146
147It is also entirely possible to just rely on HASH autovivification
148to create the slot's needed for Moose based attributes. Although
149this does somewhat restrict use of construction time attribute
150features.
151
152In short, there are several ways to go about this, it is best to
153evaluate each case based on the class you wish to extend, and the
154features you wish to employ. As always, both IRC and the mailing
155list are great ways to get help finding the best approach.
156
157=head2 Accessors
158
159=head3 How do I tell Moose to use get/set accessors?
160
161The easiest way to accomplish this is to use the C<reader> and
162C<writer> attribute options. Here is some example code:
163
164 has 'bar' => (
165 isa => 'Baz',
166 reader => 'get_bar',
167 writer => 'set_bar',
168 );
169
170Moose will still take advantage of type constraints, triggers, etc.
171when creating these methods.
172
173If you do not like this much typing, and wish it to be a default for
174your class. Please see L<Moose::Policy>, and more specifically the
175L<Moose::Policy::FollowPBP>. This will allow you to write this:
176
177 has 'bar' => (
178 isa => 'Baz',
179 is => 'rw',
180 );
181
182And have Moose create C<get_bar> and C<set_bar> instead of the usual
183C<bar>.
184
185NOTE: This B<cannot> be set globally in Moose, as this would break
186other classes which are built with Moose.
187
188=head3 How can I get Moose to inflate/deflate values in the accessor?
189
190Well, the first question to ask is if you actually need both inflate
191and deflate.
192
193If you only need to inflate, then I suggest using coercions. Here is
194some basic sample code for inflating a L<DateTime> object.
195
196 subtype 'DateTime'
197 => as 'Object'
198 => where { $_->isa('DateTime') };
199
200 coerce 'DateTime'
201 => from 'Str'
202 => via { DateTime::Format::MySQL->parse_datetime($_) };
203
204 has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
205
206This creates a custom subtype for L<DateTime> objects, then attaches
207a coercion to that subtype. The C<timestamp> attribute is then told
208to expect a C<DateTime> type, and to try and coerce it. When a C<Str>
209type is given to the C<timestamp> accessor, it will attempt to
210coerce the value into a C<DateTime> object using the code in found
211in the C<via> block.
212
213For a more detailed and complete example of coercions, see the
214L<Moose::Cookbook::Recipe5>.
215
216If you need to deflate your attribute, the current best practice is to
217add an C<around> modifier to your accessor. Here is some example code:
218
219 # a timestamp which stores as
220 # seconds from the epoch
221 has 'timestamp' => (is => 'rw', isa => 'Int');
222
223 around 'timestamp' => sub {
224 my $next = shift;
225 my ($self, $timestamp) = @_;
226 # assume we get a DateTime object ...
227 $next->($self, $timestamp->epoch);
228 };
229
230It is also possible to do deflation using coercion, but this tends
231to get quite complex and require many subtypes. An example of this
232is outside the scope of this document, ask on #moose or send a mail
233to the list.
234
235Still another option is to write a custom attribute metaclass, which
236is also outside the scope of this document, but I would be happy to
237explain it on #moose or the mailing list.
238
239=head2 Method Modfiers
240
241=head3 How can I affect the values in C<@_> using C<before>?
242
243You can't actually, C<before> only runs before the main method,
244and it cannot easily affect the execution of it. What you want is
245an C<around> method.
246
247=head3 Can I use C<before> to stop execution of a method?
248
249Yes, but only if you throw an exception. If this is too drastic a
250measure then I suggest using C<around> instead. The C<around> method
251modifier is the only modifier which can actually stop the execution
252of the main method. Here is an example:
253
254 around 'baz' => sub {
255 my $next = shift;
256 my ($self, %options) = @_;
257 if ($options{bar} eq 'foo') {
258 $next->($self, %options);
259 }
260 else {
261 return 'bar';
262 }
263 };
264
265By choosing not to call the C<$next> method, you can stop the
266execution 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
272Use 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
279This will be called when a value fails to pass the C<NaturalLessThanTen>
280constraint check.
281
734d1752 282=head3 Can I turn type constraint checking off?
283
284Not yet, but soon. This option will likely be coming in the next
285release.
286
e67a0fca 287=head1 AUTHOR
288
289Stevan Little E<lt>stevan@iinteractive.comE<gt>
290
291=head1 COPYRIGHT AND LICENSE
292
b77fdbed 293Copyright 2006, 2007 by Infinity Interactive, Inc.
e67a0fca 294
295L<http://www.iinteractive.com>
296
297This library is free software; you can redistribute it and/or modify
298it under the same terms as Perl itself.
299
300=cut