Update the "is Moose's API stable?" FAQ answer
[gitmo/Moose.git] / lib / Moose / Cookbook / FAQ.pod
CommitLineData
e67a0fca 1
2=pod
3
4=head1 NAME
5
4711f5f7 6Moose::Cookbook::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
15high-traffic services. Countless others are using Moose in
16production.
734d1752 17
2222bdc4 18As of this writing, Moose is a dependency of several hundred CPAN
19modules. L<http://cpants.perl.org/dist/used_by/Moose>
2a0f3bd3 20
21=head3 Is Moose's API stable?
22
c698114d 23Yes. The sugary API, the one 95% of users will interact with, is
24B<very stable>. Any changes will be B<100% backwards compatible>.
25
26The meta API is less set in stone. We reserve the right to tweak
27parts of it to improve efficiency or consistency. This will not be
28done lightly. We do perform deprecation cycles. We I<really>
29do not like making ourselves look bad by breaking your code.
30Submitting test cases is the best way to ensure that your code is not
31inadvertantly broken by refactoring.
2a0f3bd3 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
d03bd989 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. Of
42course using Moose itself does involve some overhead, but it
43is mostly compile time. At this point we do have some options
44available for getting the speed you need.
45
46Currently we have the option of making your classes immutable
47as a means of boosting speed. This will mean a slightly larger compile
734d1752 48time cost, but the runtime speed increase (especially in object
d03bd989 49construction) is pretty significant. This is not very well
807f6b7c 50documented yet, so please ask on the list or on #moose for more
d44714be 51information.
52
807f6b7c 53We are also discussing and experimenting with L<Module::Compile>,
54and the idea of compiling highly optimized C<.pmc> files. In
55addition, we have mapped out some core methods as candidates for
56conversion to XS.
2a0f3bd3 57
807f6b7c 58=head3 When will Moose 1.0 be ready?
2a0f3bd3 59
004222dc 60It is right now, I declared 0.18 to be "ready to use".
2a0f3bd3 61
e67a0fca 62=head2 Constructors
63
64=head3 How do I write custom constructors with Moose?
65
66Ideally, you should never write your own C<new> method, and should
67use Moose's other features to handle your specific object construction
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,
71then use the C<BUILD> method. This feature is taken directly from
72Perl 6. Every C<BUILD> method in your inheritance chain is called
73(in the correct order) immediately after the instance is constructed.
74This allows 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
ce21ecc5 81To change the parameter processing as a whole, you can use
82the C<BUILDARGS> method. The default implementation accepts key/value
83pairs or a hash reference. You can override it to take positional args,
84or any other format
85
86To change the handling of individual parameters, there are I<coercions>
5cfe3805 87(See the L<Moose::Cookbook::Basics::Recipe5> for a complete example and
a8de15f8 88explanation of coercions). With coercions it is possible to morph
ce21ecc5 89argument values into the correct expected types. This approach is the
90most flexible and robust, but does have a slightly higher learning
91curve.
e67a0fca 92
d03bd989 93=head3 How do I make non-Moose constructors work with Moose?
e67a0fca 94
e760b278 95Usually the correct approach to subclassing a non Moose class is
96delegation. Moose makes this easy using the C<handles> keyword,
97coercions, and C<lazy_build>, so subclassing is often not the
98ideal route.
99
00157674 100That said, the default Moose constructor is inherited from
e760b278 101L<Moose::Object>. When inheriting from a non-Moose class, the
102inheritance chain to L<Moose::Object> is broken. The simplest way
103to fix this is to simply explicitly inherit from L<Moose::Object>
104yourself.
105
106However, this does not always fix the issue of actually calling the Moose
3f4a85d3 107constructor. Fortunately, the modules L<MooseX::NonMoose> and
108L<MooseX::Alien> aim to make subclassing non-Moose classes easier.
109
110If neither extension fills your specific needs, you can use
111L<Class::MOP::Class/new_object>. This low-level constructor accepts the
112special C<__INSTANCE__> parameter, allowing you to instantiate your Moose
113attributes:
e67a0fca 114
115 package My::HTML::Template;
116 use Moose;
d03bd989 117
118 # explicit inheritance
e67a0fca 119 extends 'HTML::Template', 'Moose::Object';
d03bd989 120
e67a0fca 121 # explicit constructor
122 sub new {
123 my $class = shift;
124 # call HTML::Template's constructor
125 my $obj = $class->SUPER::new(@_);
126 return $class->meta->new_object(
127 # pass in the constructed object
128 # using the special key __INSTANCE__
e760b278 129 __INSTANCE__ => $obj,
130 @_, # pass in the normal args
e67a0fca 131 );
132 }
133
d03bd989 134Of course, this only works if both your Moose class and the
135inherited non-Moose class use the same instance type (typically
e760b278 136HASH refs).
137
138Note that this doesn't call C<BUILDALL> automatically, you must do that
139yourself.
e67a0fca 140
d03bd989 141Other techniques can be used as well, such as creating the object
142using C<Moose::Object::new>, but calling the inherited non-Moose
143class's initialization methods (if available).
e67a0fca 144
3f4a85d3 145In short, there are several ways to extend non-Moose classes. It is
146best to evaluate each case based on the class you wish to extend,
147and the features you wish to employ. As always, both IRC and the
148mailing list are great ways to get help finding the best approach.
e67a0fca 149
150=head2 Accessors
151
152=head3 How do I tell Moose to use get/set accessors?
153
d03bd989 154The easiest way to accomplish this is to use the C<reader> and
e67a0fca 155C<writer> attribute options. Here is some example code:
156
157 has 'bar' => (
158 isa => 'Baz',
d03bd989 159 reader => 'get_bar',
e67a0fca 160 writer => 'set_bar',
161 );
162
d03bd989 163Moose will still take advantage of type constraints, triggers, etc.
164when creating these methods.
e67a0fca 165
1a835594 166If you do not like this much typing, and wish it to be a default for your
167class, please see L<MooseX::FollowPBP>. This will allow you to write:
e67a0fca 168
169 has 'bar' => (
170 isa => 'Baz',
171 is => 'rw',
172 );
173
a8de15f8 174And have Moose create separate C<get_bar> and C<set_bar> methods
807f6b7c 175instead of a single C<bar> method.
e67a0fca 176
d03bd989 177NOTE: This B<cannot> be set globally in Moose, as that would break
e67a0fca 178other classes which are built with Moose.
179
180=head3 How can I get Moose to inflate/deflate values in the accessor?
181
d03bd989 182Well, the first question to ask is if you actually need both inflate
e67a0fca 183and deflate.
184
d03bd989 185If you only need to inflate, then I suggest using coercions. Here is
807f6b7c 186some basic sample code for inflating a L<DateTime> object:
e67a0fca 187
188 subtype 'DateTime'
189 => as 'Object'
190 => where { $_->isa('DateTime') };
d03bd989 191
e67a0fca 192 coerce 'DateTime'
193 => from 'Str'
194 => via { DateTime::Format::MySQL->parse_datetime($_) };
d03bd989 195
e67a0fca 196 has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
197
d03bd989 198This creates a custom subtype for L<DateTime> objects, then attaches
199a coercion to that subtype. The C<timestamp> attribute is then told
807f6b7c 200to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
d03bd989 201type is given to the C<timestamp> accessor, it will attempt to
202coerce the value into a C<DateTime> object using the code in found
203in the C<via> block.
e67a0fca 204
807f6b7c 205For a more comprehensive example of using coercions, see the
5cfe3805 206L<Moose::Cookbook::Basics::Recipe5>.
e67a0fca 207
d03bd989 208If you need to deflate your attribute, the current best practice is to
e67a0fca 209add an C<around> modifier to your accessor. Here is some example code:
210
d03bd989 211 # a timestamp which stores as
e67a0fca 212 # seconds from the epoch
213 has 'timestamp' => (is => 'rw', isa => 'Int');
d03bd989 214
e67a0fca 215 around 'timestamp' => sub {
216 my $next = shift;
217 my ($self, $timestamp) = @_;
218 # assume we get a DateTime object ...
219 $next->($self, $timestamp->epoch);
220 };
221
d03bd989 222It is also possible to do deflation using coercion, but this tends
223to get quite complex and require many subtypes. An example of this
224is outside the scope of this document, ask on #moose or send a mail
e67a0fca 225to the list.
226
d03bd989 227Still another option is to write a custom attribute metaclass, which
228is also outside the scope of this document, but I would be happy to
e67a0fca 229explain it on #moose or the mailing list.
230
4711f5f7 231=head2 Method Modifiers
e67a0fca 232
233=head3 How can I affect the values in C<@_> using C<before>?
234
d03bd989 235You can't, actually: C<before> only runs before the main method,
236and it cannot easily affect the method's execution. What you want is
237an C<around> method.
e67a0fca 238
239=head3 Can I use C<before> to stop execution of a method?
240
d03bd989 241Yes, but only if you throw an exception. If this is too drastic a
242measure then I suggest using C<around> instead. The C<around> method
243modifier is the only modifier which can gracefully prevent execution
e67a0fca 244of the main method. Here is an example:
245
246 around 'baz' => sub {
247 my $next = shift;
248 my ($self, %options) = @_;
807f6b7c 249 unless ($options->{bar} eq 'foo') {
250 return 'bar';
e67a0fca 251 }
807f6b7c 252 $next->($self, %options);
e67a0fca 253 };
254
d03bd989 255By choosing not to call the C<$next> method, you can stop the
e67a0fca 256execution of the main method.
257
258=head2 Type Constraints
259
260=head3 How can I have a custom error message for a type constraint?
261
807f6b7c 262Use the C<message> option when building the subtype, like so:
e67a0fca 263
d03bd989 264 subtype 'NaturalLessThanTen'
e67a0fca 265 => as 'Natural'
266 => where { $_ < 10 }
267 => message { "This number ($_) is not less than ten!" };
268
269This will be called when a value fails to pass the C<NaturalLessThanTen>
d03bd989 270constraint check.
e67a0fca 271
807f6b7c 272=head3 Can I turn off type constraint checking?
734d1752 273
d03bd989 274Not yet, but soon. This option will likely be coming in the next
734d1752 275release.
276
b36c8076 277=head2 Roles
278
279=head3 How do I get Moose to call BUILD in all my composed roles?
280
d03bd989 281See L<Moose::Cookbook::WTF> and specifically the B<Why is BUILD
dab94063 282not called for my composed roles?> question in the B<Roles> section.
b36c8076 283
dab94063 284=head3 What are Traits, and how are they different from Roles?
a8de15f8 285
457ad5fc 286In Moose, a trait is almost exactly the same thing as a role, except
287that traits typically register themselves, which allows you to refer
288to them by a short name ("Big" vs "MyApp::Role::Big").
289
290In Moose-speak, a I<Role> is usually composed into a I<class> at
291compile time, whereas a I<Trait> is usually composed into an instance
292of a class at runtime to add or modify the behavior of B<just that
293instance>.
a8de15f8 294
295Outside the context of Moose, traits and roles generally mean exactly the
296same thing. The original paper called them Traits, however Perl 6 will call
297them Roles.
298
e67a0fca 299=head1 AUTHOR
300
301Stevan Little E<lt>stevan@iinteractive.comE<gt>
302
303=head1 COPYRIGHT AND LICENSE
304
2840a3b2 305Copyright 2006-2009 by Infinity Interactive, Inc.
e67a0fca 306
307L<http://www.iinteractive.com>
308
309This library is free software; you can redistribute it and/or modify
310it under the same terms as Perl itself.
311
e760b278 312=cut