link to the list of moose-using organizations
[gitmo/Moose.git] / lib / Moose / Manual / FAQ.pod
CommitLineData
daa0fd7d 1package Moose::Manual::FAQ;
e67a0fca 2
daa0fd7d 3# ABSTRACT: Frequently asked questions about Moose
4
5__END__
e67a0fca 6
e67a0fca 7
daa0fd7d 8=pod
e67a0fca 9
10=head1 FREQUENTLY ASKED QUESTIONS
11
2a0f3bd3 12=head2 Module Stability
13
14=head3 Is Moose "production ready"?
15
2222bdc4 16Yes! Many sites with household names are using Moose to build
19440c7c 17high-traffic services. Countless others are using Moose in production.
7ff43c21 18See L<http://www.iinteractive.com/moose/about.html#organizations> for
19a partial list.
734d1752 20
2222bdc4 21As of this writing, Moose is a dependency of several hundred CPAN
22modules. L<http://cpants.perl.org/dist/used_by/Moose>
2a0f3bd3 23
24=head3 Is Moose's API stable?
25
c698114d 26Yes. The sugary API, the one 95% of users will interact with, is
27B<very stable>. Any changes will be B<100% backwards compatible>.
28
29The meta API is less set in stone. We reserve the right to tweak
30parts of it to improve efficiency or consistency. This will not be
31done lightly. We do perform deprecation cycles. We I<really>
32do not like making ourselves look bad by breaking your code.
33Submitting test cases is the best way to ensure that your code is not
7fe3cafa 34inadvertently broken by refactoring.
2a0f3bd3 35
734d1752 36=head3 I heard Moose is slow, is this true?
2a0f3bd3 37
38Again, this one is tricky, so Yes I<and> No.
39
19440c7c 40Firstly, I<nothing> in life is free, and some Moose features do cost
41more than others. It is also the policy of Moose to B<only charge you
42for the features you use>, and to do our absolute best to not place
43any extra burdens on the execution of your code for features you are
44not using. Of course using Moose itself does involve some overhead,
45but it is mostly compile time. At this point we do have some options
46available for getting the speed you need.
c32ff715 47
19440c7c 48Currently we provide the option of making your classes immutable as a
49means of boosting speed. This will mean a slightly larger compile time
50cost, but the runtime speed increase (especially in object
51construction) is pretty significant. This can be done with the
52following code:
53
54 MyClass->meta->make_immutable();
c32ff715 55
56We are regularly converting the hotspots of L<Class::MOP> to XS.
19440c7c 57Florian Ragwitz and Yuval Kogman are currently working on a way to
58compile your accessors and instances directly into C, so that everyone
59can enjoy blazing fast OO.
2a0f3bd3 60
807f6b7c 61=head3 When will Moose 1.0 be ready?
2a0f3bd3 62
19440c7c 63Moose is ready now! Stevan Little declared 0.18, released in March
642007, to be "ready to use".
2a0f3bd3 65
e67a0fca 66=head2 Constructors
67
68=head3 How do I write custom constructors with Moose?
69
19440c7c 70Ideally, you should never write your own C<new> method, and should use
71Moose's other features to handle your specific object construction
e67a0fca 72needs. Here are a few scenarios, and the Moose way to solve them;
73
d03bd989 74If you need to call initialization code post instance construction,
19440c7c 75then use the C<BUILD> method. This feature is taken directly from Perl
766. Every C<BUILD> method in your inheritance chain is called (in the
77correct order) immediately after the instance is constructed. This
78allows you to ensure that all your superclasses are initialized
e67a0fca 79properly as well. This is the best approach to take (when possible)
dab94063 80because it makes subclassing your class much easier.
e67a0fca 81
d03bd989 82If you need to affect the constructor's parameters prior to the
e67a0fca 83instance actually being constructed, you have a number of options.
84
19440c7c 85To change the parameter processing as a whole, you can use the
86C<BUILDARGS> method. The default implementation accepts key/value
87pairs or a hash reference. You can override it to take positional
88args, or any other format
ce21ecc5 89
19440c7c 90To change the handling of individual parameters, there are
91I<coercions> (See the L<Moose::Cookbook::Basics::Recipe5> for a
92complete example and explanation of coercions). With coercions it is
93possible to morph argument values into the correct expected
94types. This approach is the most flexible and robust, but does have a
95slightly higher learning curve.
e67a0fca 96
d03bd989 97=head3 How do I make non-Moose constructors work with Moose?
e67a0fca 98
6c17df8f 99Usually the correct approach to subclassing a non-Moose class is
e760b278 100delegation. Moose makes this easy using the C<handles> keyword,
19440c7c 101coercions, and C<lazy_build>, so subclassing is often not the ideal
102route.
e760b278 103
fe4975b3 104That said, if you really need to inherit from a non-Moose class, see
cc7dafef 105L<Moose::Cookbook::Basics::Recipe11> for an example of how to do it,
106or take a look at L<Moose::Manual::MooseX/"MooseX::NonMoose">.
e67a0fca 107
108=head2 Accessors
109
110=head3 How do I tell Moose to use get/set accessors?
111
d03bd989 112The easiest way to accomplish this is to use the C<reader> and
6c17df8f 113C<writer> attribute options:
e67a0fca 114
115 has 'bar' => (
116 isa => 'Baz',
d03bd989 117 reader => 'get_bar',
e67a0fca 118 writer => 'set_bar',
119 );
120
d03bd989 121Moose will still take advantage of type constraints, triggers, etc.
122when creating these methods.
e67a0fca 123
19440c7c 124If you do not like this much typing, and wish it to be a default for
125your classes, please see L<MooseX::FollowPBP>. This extension will
126allow you to write:
e67a0fca 127
128 has 'bar' => (
129 isa => 'Baz',
130 is => 'rw',
131 );
132
19440c7c 133Moose will create separate C<get_bar> and C<set_bar> methods instead
134of a single C<bar> method.
135
136If you like C<bar> and C<set_bar>, see
137L<MooseX::SemiAffordanceAccessor>.
e67a0fca 138
d03bd989 139NOTE: This B<cannot> be set globally in Moose, as that would break
6c17df8f 140other classes which are built with Moose. You can still save on typing
141by defining a new L<MyApp::Moose> that exports Moose's sugar and then
19440c7c 142turns on L<MooseX::FollowPBP>. See
143L<Moose::Cookbook::Extending::Recipe4>.
e67a0fca 144
6c17df8f 145=head3 How can I inflate/deflate values in accessors?
e67a0fca 146
d03bd989 147Well, the first question to ask is if you actually need both inflate
e67a0fca 148and deflate.
149
8b870d0e 150If you only need to inflate, then we suggest using coercions. Here is
807f6b7c 151some basic sample code for inflating a L<DateTime> object:
e67a0fca 152
6c17df8f 153 class_type 'DateTime';
d03bd989 154
e67a0fca 155 coerce 'DateTime'
156 => from 'Str'
d8e332d5 157 => via { DateTime::Format::MySQL->parse_datetime($_) };
d03bd989 158
e67a0fca 159 has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
160
6c17df8f 161This creates a custom type for L<DateTime> objects, then attaches
162a coercion to that type. The C<timestamp> attribute is then told
807f6b7c 163to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
d03bd989 164type is given to the C<timestamp> accessor, it will attempt to
165coerce the value into a C<DateTime> object using the code in found
166in the C<via> block.
e67a0fca 167
807f6b7c 168For a more comprehensive example of using coercions, see the
5cfe3805 169L<Moose::Cookbook::Basics::Recipe5>.
e67a0fca 170
19440c7c 171If you need to deflate your attribute's value, the current best
172practice is to add an C<around> modifier to your accessor:
e67a0fca 173
d03bd989 174 # a timestamp which stores as
e67a0fca 175 # seconds from the epoch
176 has 'timestamp' => (is => 'rw', isa => 'Int');
d03bd989 177
e67a0fca 178 around 'timestamp' => sub {
179 my $next = shift;
24d8fc0d 180 my $self = shift;
181
182 return $self->$next unless @_;
183
e67a0fca 184 # assume we get a DateTime object ...
24d8fc0d 185 my $timestamp = shift;
186 return $self->$next( $timestamp->epoch );
e67a0fca 187 };
188
19440c7c 189It is also possible to do deflation using coercion, but this tends to
190get quite complex and require many subtypes. An example of this is
191outside the scope of this document, ask on #moose or send a mail to
192the list.
e67a0fca 193
d03bd989 194Still another option is to write a custom attribute metaclass, which
8b870d0e 195is also outside the scope of this document, but we would be happy to
e67a0fca 196explain it on #moose or the mailing list.
197
19440c7c 198=head3 I created an attribute, where are my accessors?
199
200Accessors are B<not> created implicitly, you B<must> ask Moose to
201create them for you. My guess is that you have this:
202
203 has 'foo' => (isa => 'Bar');
204
205when what you really want to say is:
206
207 has 'foo' => (isa => 'Bar', is => 'rw');
208
209The reason this is so is because it is a perfectly valid use case to
210I<not> have an accessor. The simplest one is that you want to write
211your own. If Moose created one automatically, then because of the
212order in which classes are constructed, Moose would overwrite your
213custom accessor. You wouldn't want that would you?
214
4711f5f7 215=head2 Method Modifiers
e67a0fca 216
217=head3 How can I affect the values in C<@_> using C<before>?
218
19440c7c 219You can't, actually: C<before> only runs before the main method, and
220it cannot easily affect the method's execution.
e30e57c6 221
222You similarly can't use C<after> to affect the return value of a
223method.
224
225We limit C<before> and C<after> because this lets you write more
226concise code. You do not have to worry about passing C<@_> to the
6c17df8f 227original method, or forwarding its return value (being careful to
228preserve context).
e30e57c6 229
19440c7c 230The C<around> method modifier has neither of these limitations, but is
231a little more verbose.
e67a0fca 232
233=head3 Can I use C<before> to stop execution of a method?
234
d03bd989 235Yes, but only if you throw an exception. If this is too drastic a
8b870d0e 236measure then we suggest using C<around> instead. The C<around> method
d03bd989 237modifier is the only modifier which can gracefully prevent execution
e67a0fca 238of the main method. Here is an example:
239
6c17df8f 240 around 'baz' => sub {
241 my $next = shift;
242 my ($self, %options) = @_;
243 unless ($options->{bar} eq 'foo') {
244 return 'bar';
245 }
3ae20eb6 246 $self->$next(%options);
6c17df8f 247 };
e67a0fca 248
d03bd989 249By choosing not to call the C<$next> method, you can stop the
e67a0fca 250execution of the main method.
251
19440c7c 252=head3 Why can't I see return values in an C<after> modifier?
253
254As with the C<before> modifier, the C<after> modifier is simply called
255I<after> the main method. It is passed the original contents of C<@_>
256and B<not> the return values of the main method.
257
258Again, the arguments are too lengthy as to why this has to be. And as
259with C<before> I recommend using an C<around> modifier instead. Here
260is some sample code:
261
262 around 'foo' => sub {
263 my $next = shift;
264 my ($self, @args) = @_;
265 my @rv = $next->($self, @args);
266 # do something silly with the return values
267 return reverse @rv;
268 };
269
e67a0fca 270=head2 Type Constraints
271
6c17df8f 272=head3 How can I provide a custom error message for a type constraint?
e67a0fca 273
6c17df8f 274Use the C<message> option when building the subtype:
e67a0fca 275
d03bd989 276 subtype 'NaturalLessThanTen'
e67a0fca 277 => as 'Natural'
278 => where { $_ < 10 }
279 => message { "This number ($_) is not less than ten!" };
280
6c17df8f 281This C<message> block will be called when a value fails to pass the
282C<NaturalLessThanTen> constraint check.
e67a0fca 283
807f6b7c 284=head3 Can I turn off type constraint checking?
734d1752 285
19440c7c 286Not yet. This option may come in a future release.
734d1752 287
6b5a29f4 288=head3 My coercions stopped working with recent Moose, why did you break it?
289
290Moose 0.76 fixed a case where Coercions were being applied even if the original constraint passed. This has caused some edge cases to fail where people were doing something like
291
292 subtype Address => as 'Str';
293 coerce Address => from Str => via { get_address($_) };
cc7dafef 294
6b5a29f4 295Which is not what they intended. The Type Constraint C<Address> is too loose in this case, it is saying that all Strings are Addresses, which is obviously not the case. The solution is to provide a where clause that properly restricts the Type Constraint.
296
297 subtype Address => as Str => where { looks_like_address($_) };
298
299This will allow the coercion to apply only to strings that fail to look like an Address.
300
b36c8076 301=head2 Roles
302
19440c7c 303=head3 Why is BUILD not called for my composed roles?
304
beb804d9 305C<BUILD> is never called in composed roles. The primary reason is that
19440c7c 306roles are B<not> order sensitive. Roles are composed in such a way
307that the order of composition does not matter (for information on the
308deeper theory of this read the original traits papers here
309L<http://www.iam.unibe.ch/~scg/Research/Traits/>).
310
311Because roles are essentially unordered, it would be impossible to
beb804d9 312determine the order in which to execute the C<BUILD> methods.
19440c7c 313
314As for alternate solutions, there are a couple.
315
316=over 4
b36c8076 317
19440c7c 318=item *
319
320Using a combination of lazy and default in your attributes to defer
321initialization (see the Binary Tree example in the cookbook for a good
322example of lazy/default usage L<Moose::Cookbook::Basics::Recipe3>)
323
324=item *
325
326Use attribute triggers, which fire after an attribute is set, to
327facilitate initialization. These are described in the L<Moose> docs,
328and examples can be found in the test suite.
329
330=back
331
332In general, roles should not I<require> initialization; they should
333either provide sane defaults or should be documented as needing
334specific initialization. One such way to "document" this is to have a
335separate attribute initializer which is required for the role. Here is
336an example of how to do this:
337
338 package My::Role;
339 use Moose::Role;
340
341 has 'height' => (
342 is => 'rw',
343 isa => 'Int',
344 lazy => 1,
345 default => sub {
346 my $self = shift;
347 $self->init_height;
348 }
349 );
350
351 requires 'init_height';
352
353In this example, the role will not compose successfully unless the
354class provides a C<init_height> method.
355
356If none of those solutions work, then it is possible that a role is
357not the best tool for the job, and you really should be using
358classes. Or, at the very least, you should reduce the amount of
359functionality in your role so that it does not require initialization.
b36c8076 360
dab94063 361=head3 What are Traits, and how are they different from Roles?
a8de15f8 362
457ad5fc 363In Moose, a trait is almost exactly the same thing as a role, except
364that traits typically register themselves, which allows you to refer
365to them by a short name ("Big" vs "MyApp::Role::Big").
366
367In Moose-speak, a I<Role> is usually composed into a I<class> at
368compile time, whereas a I<Trait> is usually composed into an instance
19440c7c 369of a class at runtime to add or modify the behavior of B<just that
370instance>.
371
372Outside the context of Moose, traits and roles generally mean exactly
373the same thing. The original paper called them Traits, however Perl 6
374will call them Roles.
375
376=head2 Moose and Subroutine Attributes
377
378=head3 Why don't subroutine attributes I inherited from a superclass work?
379
380Currently when you subclass a module, this is done at runtime with the
381C<extends> keyword but attributes are checked at compile time by
382Perl. To make attributes work, you must place C<extends> in a C<BEGIN>
383block so that the attribute handlers will be available at compile time
384like this:
385
386 BEGIN { extends qw/Foo/ }
387
388Note that we're talking about Perl's subroutine attributes here, not
389Moose attributes:
a8de15f8 390
19440c7c 391 sub foo : Bar(27) { ... }
a8de15f8 392
e760b278 393=cut