6 Moose::Cookbook::FAQ - Frequently asked questions about Moose
8 =head1 FREQUENTLY ASKED QUESTIONS
10 =head2 Module Stability
12 =head3 Is Moose "production ready"?
14 Yes. I have several medium-to-large-ish web applications in
15 production using Moose, they have been running without
16 issue now for well over a year.
18 At C<$work> we are re-writing our core offering to use Moose,
19 so it's continued development is assured.
21 Several other people on #moose either have apps in production
22 which use Moose, or are in the process of deploying sites
25 =head3 Is Moose's API stable?
27 Yes and No. The external API, the one 90% of users will interact
28 with, is B<very stable> and any changes B<will be 100% backwards
29 compatible>. The introspection API is I<mostly> stable; I still
30 reserve the right to tweak that if needed, but I will do my
31 absolute best to maintain backwards compatibility here as well.
33 =head3 I heard Moose is slow, is this true?
35 Again, this one is tricky, so Yes I<and> No.
37 First let me say that I<nothing> in life is free, and that some
38 Moose features do cost more than others. It is also the
39 policy of Moose to B<only charge you for the features you use>,
40 and to do our absolute best to not place any extra burdens on
41 the execution of your code for features you are not using. Of
42 course using Moose itself does involve some overhead, but it
43 is mostly compile time. At this point we do have some options
44 available for getting the speed you need.
46 Currently we have the option of making your classes immutable
47 as a means of boosting speed. This will mean a slightly larger compile
48 time cost, but the runtime speed increase (especially in object
49 construction) is pretty significant. This is not very well
50 documented yet, so please ask on the list or on #moose for more
53 We are also discussing and experimenting with L<Module::Compile>,
54 and the idea of compiling highly optimized C<.pmc> files. In
55 addition, we have mapped out some core methods as candidates for
58 =head3 When will Moose 1.0 be ready?
60 It is right now, I declared 0.18 to be "ready to use".
64 =head3 How do I write custom constructors with Moose?
66 Ideally, you should never write your own C<new> method, and should
67 use Moose's other features to handle your specific object construction
68 needs. Here are a few scenarios, and the Moose way to solve them;
70 If you need to call initialization code post instance construction,
71 then use the C<BUILD> method. This feature is taken directly from
72 Perl 6. Every C<BUILD> method in your inheritance chain is called
73 (in the correct order) immediately after the instance is constructed.
74 This allows you to ensure that all your superclasses are initialized
75 properly as well. This is the best approach to take (when possible)
76 because it makes sub classing your class much easier.
78 If you need to affect the constructor's parameters prior to the
79 instance actually being constructed, you have a number of options.
81 First, there are I<coercions> (See the L<Moose::Cookbook::Recipe5>
82 for a complete example and explaination of coercions). With
83 coercions it is possible to morph argument values into the correct
84 expected types. This approach is the most flexible and robust, but
85 does have a slightly higher learning curve.
87 Second, using an C<around> method modifier on C<new> can be an
88 effective way to affect the contents of C<@_> prior to letting
89 Moose deal with it. This carries with it the extra burden for
90 your subclasses, in that they have to be sure to explicitly
91 call your C<new> and/or work around your C<new> to get to the
92 version from L<Moose::Object>.
94 The last approach is to use the standard Perl technique of calling
95 the C<SUPER::new> within your own custom version of C<new>. This,
96 of course, brings with it all the issues of the C<around> solution
97 as well as any issues C<SUPER::> might add.
99 In short, try to use C<BUILD> and coercions, they are your best
102 =head3 How do I make non-Moose constructors work with Moose?
104 Usually the correct approach to subclassing a non Moose class is
105 delegation. Moose makes this easy using the C<handles> keyword,
106 coercions, and C<lazy_build>, so subclassing is often not the
109 That said, the default Moose constructors is inherited from
110 L<Moose::Object>. When inheriting from a non-Moose class, the
111 inheritance chain to L<Moose::Object> is broken. The simplest way
112 to fix this is to simply explicitly inherit from L<Moose::Object>
115 However, this does not always fix the issue of actually calling the Moose
116 constructor. Fortunately L<Class::MOP::Class/new_object>, the low level
117 constructor, accepts the special C<__INSTANCE__> parameter, allowing you to
118 instantiate your Moose attributes:
120 package My::HTML::Template;
123 # explicit inheritance
124 extends 'HTML::Template', 'Moose::Object';
126 # explicit constructor
129 # call HTML::Template's constructor
130 my $obj = $class->SUPER::new(@_);
131 return $class->meta->new_object(
132 # pass in the constructed object
133 # using the special key __INSTANCE__
134 __INSTANCE__ => $obj,
135 @_, # pass in the normal args
139 Of course, this only works if both your Moose class and the
140 inherited non-Moose class use the same instance type (typically
143 Note that this doesn't call C<BUILDALL> automatically, you must do that
146 Other techniques can be used as well, such as creating the object
147 using C<Moose::Object::new>, but calling the inherited non-Moose
148 class's initialization methods (if available).
150 It is also entirely possible to just rely on HASH autovivification
151 to create the slots needed for Moose based attributes, although this
152 does restrict use of construction time attribute features somewhat.
154 In short, there are several ways to go about this, it is best to
155 evaluate each case based on the class you wish to extend, and the
156 features you wish to employ. As always, both IRC and the mailing
157 list are great ways to get help finding the best approach.
161 =head3 How do I tell Moose to use get/set accessors?
163 The easiest way to accomplish this is to use the C<reader> and
164 C<writer> attribute options. Here is some example code:
172 Moose will still take advantage of type constraints, triggers, etc.
173 when creating these methods.
175 If you do not like this much typing, and wish it to be a default for
176 your class, please see L<Moose::Policy>, and more specifically
177 L<Moose::Policy::FollowPBP>. This will allow you to write:
184 And have Moose create seperate C<get_bar> and C<set_bar> methods
185 instead of a single C<bar> method.
187 NOTE: This B<cannot> be set globally in Moose, as that would break
188 other classes which are built with Moose.
190 =head3 How can I get Moose to inflate/deflate values in the accessor?
192 Well, the first question to ask is if you actually need both inflate
195 If you only need to inflate, then I suggest using coercions. Here is
196 some basic sample code for inflating a L<DateTime> object:
200 => where { $_->isa('DateTime') };
204 => via { DateTime::Format::MySQL->parse_datetime($_) };
206 has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
208 This creates a custom subtype for L<DateTime> objects, then attaches
209 a coercion to that subtype. The C<timestamp> attribute is then told
210 to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
211 type is given to the C<timestamp> accessor, it will attempt to
212 coerce the value into a C<DateTime> object using the code in found
215 For a more comprehensive example of using coercions, see the
216 L<Moose::Cookbook::Recipe5>.
218 If you need to deflate your attribute, the current best practice is to
219 add an C<around> modifier to your accessor. Here is some example code:
221 # a timestamp which stores as
222 # seconds from the epoch
223 has 'timestamp' => (is => 'rw', isa => 'Int');
225 around 'timestamp' => sub {
227 my ($self, $timestamp) = @_;
228 # assume we get a DateTime object ...
229 $next->($self, $timestamp->epoch);
232 It is also possible to do deflation using coercion, but this tends
233 to get quite complex and require many subtypes. An example of this
234 is outside the scope of this document, ask on #moose or send a mail
237 Still another option is to write a custom attribute metaclass, which
238 is also outside the scope of this document, but I would be happy to
239 explain it on #moose or the mailing list.
241 =head2 Method Modifiers
243 =head3 How can I affect the values in C<@_> using C<before>?
245 You can't, actually: C<before> only runs before the main method,
246 and it cannot easily affect the method's execution. What you want is
249 =head3 Can I use C<before> to stop execution of a method?
251 Yes, but only if you throw an exception. If this is too drastic a
252 measure then I suggest using C<around> instead. The C<around> method
253 modifier is the only modifier which can gracefully prevent execution
254 of the main method. Here is an example:
256 around 'baz' => sub {
258 my ($self, %options) = @_;
259 unless ($options->{bar} eq 'foo') {
262 $next->($self, %options);
265 By choosing not to call the C<$next> method, you can stop the
266 execution of the main method.
268 =head2 Type Constraints
270 =head3 How can I have a custom error message for a type constraint?
272 Use the C<message> option when building the subtype, like so:
274 subtype 'NaturalLessThanTen'
277 => message { "This number ($_) is not less than ten!" };
279 This will be called when a value fails to pass the C<NaturalLessThanTen>
282 =head3 Can I turn off type constraint checking?
284 Not yet, but soon. This option will likely be coming in the next
289 =head3 How do I get Moose to call BUILD in all my composed roles?
291 See L<Moose::Cookbook::WTF> and specifically the B<How come BUILD
292 is not called for my composed roles?> question in the B<Roles> section.
296 Stevan Little E<lt>stevan@iinteractive.comE<gt>
298 =head1 COPYRIGHT AND LICENSE
300 Copyright 2006-2008 by Infinity Interactive, Inc.
302 L<http://www.iinteractive.com>
304 This library is free software; you can redistribute it and/or modify
305 it under the same terms as Perl itself.