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