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