don't assume search.cpan.org-format anchors
[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
e67a0fca 56=head2 Constructors
57
58=head3 How do I write custom constructors with Moose?
59
19440c7c 60Ideally, you should never write your own C<new> method, and should use
61Moose's other features to handle your specific object construction
e67a0fca 62needs. Here are a few scenarios, and the Moose way to solve them;
63
d03bd989 64If you need to call initialization code post instance construction,
19440c7c 65then use the C<BUILD> method. This feature is taken directly from Perl
666. Every C<BUILD> method in your inheritance chain is called (in the
67correct order) immediately after the instance is constructed. This
68allows you to ensure that all your superclasses are initialized
e67a0fca 69properly as well. This is the best approach to take (when possible)
dab94063 70because it makes subclassing your class much easier.
e67a0fca 71
d03bd989 72If you need to affect the constructor's parameters prior to the
e67a0fca 73instance actually being constructed, you have a number of options.
74
19440c7c 75To change the parameter processing as a whole, you can use the
76C<BUILDARGS> method. The default implementation accepts key/value
77pairs or a hash reference. You can override it to take positional
78args, or any other format
ce21ecc5 79
19440c7c 80To change the handling of individual parameters, there are
81I<coercions> (See the L<Moose::Cookbook::Basics::Recipe5> for a
82complete example and explanation of coercions). With coercions it is
83possible to morph argument values into the correct expected
84types. This approach is the most flexible and robust, but does have a
85slightly higher learning curve.
e67a0fca 86
d03bd989 87=head3 How do I make non-Moose constructors work with Moose?
e67a0fca 88
6c17df8f 89Usually the correct approach to subclassing a non-Moose class is
e760b278 90delegation. Moose makes this easy using the C<handles> keyword,
19440c7c 91coercions, and C<lazy_build>, so subclassing is often not the ideal
92route.
e760b278 93
fe4975b3 94That said, if you really need to inherit from a non-Moose class, see
cc7dafef 95L<Moose::Cookbook::Basics::Recipe11> for an example of how to do it,
96or take a look at L<Moose::Manual::MooseX/"MooseX::NonMoose">.
e67a0fca 97
98=head2 Accessors
99
100=head3 How do I tell Moose to use get/set accessors?
101
d03bd989 102The easiest way to accomplish this is to use the C<reader> and
6c17df8f 103C<writer> attribute options:
e67a0fca 104
105 has 'bar' => (
106 isa => 'Baz',
d03bd989 107 reader => 'get_bar',
e67a0fca 108 writer => 'set_bar',
109 );
110
d03bd989 111Moose will still take advantage of type constraints, triggers, etc.
112when creating these methods.
e67a0fca 113
19440c7c 114If you do not like this much typing, and wish it to be a default for
115your classes, please see L<MooseX::FollowPBP>. This extension will
116allow you to write:
e67a0fca 117
118 has 'bar' => (
119 isa => 'Baz',
120 is => 'rw',
121 );
122
19440c7c 123Moose will create separate C<get_bar> and C<set_bar> methods instead
124of a single C<bar> method.
125
126If you like C<bar> and C<set_bar>, see
127L<MooseX::SemiAffordanceAccessor>.
e67a0fca 128
d03bd989 129NOTE: This B<cannot> be set globally in Moose, as that would break
6c17df8f 130other classes which are built with Moose. You can still save on typing
131by defining a new L<MyApp::Moose> that exports Moose's sugar and then
19440c7c 132turns on L<MooseX::FollowPBP>. See
133L<Moose::Cookbook::Extending::Recipe4>.
e67a0fca 134
6c17df8f 135=head3 How can I inflate/deflate values in accessors?
e67a0fca 136
d03bd989 137Well, the first question to ask is if you actually need both inflate
e67a0fca 138and deflate.
139
8b870d0e 140If you only need to inflate, then we suggest using coercions. Here is
807f6b7c 141some basic sample code for inflating a L<DateTime> object:
e67a0fca 142
6c17df8f 143 class_type 'DateTime';
d03bd989 144
e67a0fca 145 coerce 'DateTime'
146 => from 'Str'
d8e332d5 147 => via { DateTime::Format::MySQL->parse_datetime($_) };
d03bd989 148
e67a0fca 149 has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
150
6c17df8f 151This creates a custom type for L<DateTime> objects, then attaches
152a coercion to that type. The C<timestamp> attribute is then told
807f6b7c 153to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
d03bd989 154type is given to the C<timestamp> accessor, it will attempt to
155coerce the value into a C<DateTime> object using the code in found
156in the C<via> block.
e67a0fca 157
807f6b7c 158For a more comprehensive example of using coercions, see the
5cfe3805 159L<Moose::Cookbook::Basics::Recipe5>.
e67a0fca 160
19440c7c 161If you need to deflate your attribute's value, the current best
162practice is to add an C<around> modifier to your accessor:
e67a0fca 163
d03bd989 164 # a timestamp which stores as
e67a0fca 165 # seconds from the epoch
166 has 'timestamp' => (is => 'rw', isa => 'Int');
d03bd989 167
e67a0fca 168 around 'timestamp' => sub {
169 my $next = shift;
24d8fc0d 170 my $self = shift;
171
172 return $self->$next unless @_;
173
e67a0fca 174 # assume we get a DateTime object ...
24d8fc0d 175 my $timestamp = shift;
176 return $self->$next( $timestamp->epoch );
e67a0fca 177 };
178
19440c7c 179It is also possible to do deflation using coercion, but this tends to
180get quite complex and require many subtypes. An example of this is
181outside the scope of this document, ask on #moose or send a mail to
182the list.
e67a0fca 183
d03bd989 184Still another option is to write a custom attribute metaclass, which
8b870d0e 185is also outside the scope of this document, but we would be happy to
e67a0fca 186explain it on #moose or the mailing list.
187
4711f5f7 188=head2 Method Modifiers
e67a0fca 189
190=head3 How can I affect the values in C<@_> using C<before>?
191
19440c7c 192You can't, actually: C<before> only runs before the main method, and
193it cannot easily affect the method's execution.
e30e57c6 194
195You similarly can't use C<after> to affect the return value of a
196method.
197
198We limit C<before> and C<after> because this lets you write more
199concise code. You do not have to worry about passing C<@_> to the
6c17df8f 200original method, or forwarding its return value (being careful to
201preserve context).
e30e57c6 202
19440c7c 203The C<around> method modifier has neither of these limitations, but is
204a little more verbose.
e67a0fca 205
5e8927d6 206Alternatively, the L<MooseX::Mangle> extension provides the
207C<mangle_args> function, which does allow you to affect C<@_>.
208
e67a0fca 209=head3 Can I use C<before> to stop execution of a method?
210
d03bd989 211Yes, but only if you throw an exception. If this is too drastic a
8b870d0e 212measure then we suggest using C<around> instead. The C<around> method
d03bd989 213modifier is the only modifier which can gracefully prevent execution
e67a0fca 214of the main method. Here is an example:
215
6c17df8f 216 around 'baz' => sub {
217 my $next = shift;
218 my ($self, %options) = @_;
219 unless ($options->{bar} eq 'foo') {
220 return 'bar';
221 }
3ae20eb6 222 $self->$next(%options);
6c17df8f 223 };
e67a0fca 224
d03bd989 225By choosing not to call the C<$next> method, you can stop the
e67a0fca 226execution of the main method.
227
5e8927d6 228Alternatively, the L<MooseX::Mangle> extension provides the
229C<guard> function, which will conditionally prevent execution
230of the original method.
231
19440c7c 232=head3 Why can't I see return values in an C<after> modifier?
233
234As with the C<before> modifier, the C<after> modifier is simply called
235I<after> the main method. It is passed the original contents of C<@_>
236and B<not> the return values of the main method.
237
238Again, the arguments are too lengthy as to why this has to be. And as
239with C<before> I recommend using an C<around> modifier instead. Here
240is some sample code:
241
242 around 'foo' => sub {
243 my $next = shift;
244 my ($self, @args) = @_;
245 my @rv = $next->($self, @args);
246 # do something silly with the return values
247 return reverse @rv;
248 };
249
5e8927d6 250Alternatively, the L<MooseX::Mangle> extension provides the
251C<mangle_return> function, which allows modifying the return values
252of the original method.
253
e67a0fca 254=head2 Type Constraints
255
6c17df8f 256=head3 How can I provide a custom error message for a type constraint?
e67a0fca 257
6c17df8f 258Use the C<message> option when building the subtype:
e67a0fca 259
d03bd989 260 subtype 'NaturalLessThanTen'
e67a0fca 261 => as 'Natural'
262 => where { $_ < 10 }
263 => message { "This number ($_) is not less than ten!" };
264
6c17df8f 265This C<message> block will be called when a value fails to pass the
266C<NaturalLessThanTen> constraint check.
e67a0fca 267
807f6b7c 268=head3 Can I turn off type constraint checking?
734d1752 269
19440c7c 270Not yet. This option may come in a future release.
734d1752 271
6b5a29f4 272=head3 My coercions stopped working with recent Moose, why did you break it?
273
ed809fa3 274Moose 0.76 fixed a case where coercions were being applied even if the original
275constraint passed. This has caused some edge cases to fail where people were
276doing something like
6b5a29f4 277
ed809fa3 278 subtype 'Address', as 'Str';
279 coerce 'Address', from 'Str', via { get_address($_) };
cc7dafef 280
ed809fa3 281This is not what they intended, because the type constraint C<Address> is too
282loose in this case. It is saying that all strings are Addresses, which is
283obviously not the case. The solution is to provide a C<where> clause that
284properly restricts the type constraint:
6b5a29f4 285
ed809fa3 286 subtype 'Address', as 'Str', where { looks_like_address($_) };
6b5a29f4 287
ed809fa3 288This will allow the coercion to apply only to strings that fail to look like an
289Address.
6b5a29f4 290
b36c8076 291=head2 Roles
292
19440c7c 293=head3 Why is BUILD not called for my composed roles?
294
beb804d9 295C<BUILD> is never called in composed roles. The primary reason is that
19440c7c 296roles are B<not> order sensitive. Roles are composed in such a way
297that the order of composition does not matter (for information on the
298deeper theory of this read the original traits papers here
299L<http://www.iam.unibe.ch/~scg/Research/Traits/>).
300
301Because roles are essentially unordered, it would be impossible to
beb804d9 302determine the order in which to execute the C<BUILD> methods.
19440c7c 303
304As for alternate solutions, there are a couple.
305
306=over 4
b36c8076 307
19440c7c 308=item *
309
310Using a combination of lazy and default in your attributes to defer
311initialization (see the Binary Tree example in the cookbook for a good
312example of lazy/default usage L<Moose::Cookbook::Basics::Recipe3>)
313
314=item *
315
316Use attribute triggers, which fire after an attribute is set, to
317facilitate initialization. These are described in the L<Moose> docs,
318and examples can be found in the test suite.
319
320=back
321
322In general, roles should not I<require> initialization; they should
323either provide sane defaults or should be documented as needing
324specific initialization. One such way to "document" this is to have a
325separate attribute initializer which is required for the role. Here is
326an example of how to do this:
327
328 package My::Role;
329 use Moose::Role;
330
331 has 'height' => (
332 is => 'rw',
333 isa => 'Int',
334 lazy => 1,
335 default => sub {
336 my $self = shift;
337 $self->init_height;
338 }
339 );
340
341 requires 'init_height';
342
343In this example, the role will not compose successfully unless the
344class provides a C<init_height> method.
345
346If none of those solutions work, then it is possible that a role is
347not the best tool for the job, and you really should be using
348classes. Or, at the very least, you should reduce the amount of
349functionality in your role so that it does not require initialization.
b36c8076 350
0c13ed90 351=head3 What are traits, and how are they different from roles?
a8de15f8 352
457ad5fc 353In Moose, a trait is almost exactly the same thing as a role, except
354that traits typically register themselves, which allows you to refer
355to them by a short name ("Big" vs "MyApp::Role::Big").
356
357In Moose-speak, a I<Role> is usually composed into a I<class> at
358compile time, whereas a I<Trait> is usually composed into an instance
19440c7c 359of a class at runtime to add or modify the behavior of B<just that
360instance>.
361
362Outside the context of Moose, traits and roles generally mean exactly
0c13ed90 363the same thing. The original paper called them traits, but Perl 6
364will call them roles.
19440c7c 365
be2630cf 366=head3 Can an attribute-generated method (e.g. an accessor) satisfy requires?
367
368Yes, just be sure to consume the role I<after> declaring your
aa0e1400 369attribute. L<Moose::Manual::Roles/Required Attributes> provides
be2630cf 370an example:
371
372 package Breakable;
373 use Moose::Role;
374 requires 'stress';
375
376 package Car;
377 use Moose;
be2630cf 378 has 'stress' => ( is => 'rw', isa => 'Int' );
5d299768 379 with 'Breakable';
be2630cf 380
381If you mistakenly consume the C<Breakable> role before declaring your
382C<stress> attribute, you would see an error like this:
383
384 'Breakable' requires the method 'stress' to be implemented by 'Car' at...
385
19440c7c 386=head2 Moose and Subroutine Attributes
387
388=head3 Why don't subroutine attributes I inherited from a superclass work?
389
0c13ed90 390Currently when subclassing a module is done at runtime with the
391C<extends> keyword, but attributes are checked at compile time by
19440c7c 392Perl. To make attributes work, you must place C<extends> in a C<BEGIN>
0c13ed90 393block so that the attribute handlers will be available at compile time,
19440c7c 394like this:
395
396 BEGIN { extends qw/Foo/ }
397
398Note that we're talking about Perl's subroutine attributes here, not
399Moose attributes:
a8de15f8 400
19440c7c 401 sub foo : Bar(27) { ... }
a8de15f8 402
e760b278 403=cut