rudementary support for attribute traits
[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
3796382a 14Yes. I have three medium-to-large-ish web applications in
734d1752 15production using Moose, they have been running without
16issue now for almost a year.
17
18At $work we are re-writing our core offering to use Moose,
19so it's continued development is assured.
20
21Several other people on #moose either have apps in production
22which use Moose, or are in the process of deploying sites
23which use Moose.
2a0f3bd3 24
25=head3 Is Moose's API stable?
26
27Yes and No. The external API, the one 90% of users will interact
28with, is B<very stable> and any changes B<will be 100% backwards
807f6b7c 29compatible>. The introspection API is I<mostly> stable; I still
2a0f3bd3 30reserve the right to tweak that if needed, but I will do my
4711f5f7 31absolute best to maintain backwards compatibility here as well.
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
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
d44714be 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.
2a0f3bd3 45
734d1752 46Currently we have the option of making your classes immutable
47as a means of boosting speed. This will mean a larger compile
48time cost, but the runtime speed increase (especially in object
4711f5f7 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
3796382a 60It is right now, I just haven't bumped the version number up yet.
2a0f3bd3 61
3796382a 62I still have some more internal TODO items I would like to complete
63before I would even consider bumping it to 1.0.
2a0f3bd3 64
e67a0fca 65=head2 Constructors
66
67=head3 How do I write custom constructors with Moose?
68
69Ideally, you should never write your own C<new> method, and should
70use Moose's other features to handle your specific object construction
71needs. Here are a few scenarios, and the Moose way to solve them;
72
4711f5f7 73If you need to call initialization code post instance construction,
e67a0fca 74then use the C<BUILD> method. This feature is taken directly from
4711f5f7 75Perl 6. Every C<BUILD> method in your inheritance chain is called
e67a0fca 76(in the correct order) immediately after the instance is constructed.
77This allows you to ensure that all your superclasses are initialized
78properly as well. This is the best approach to take (when possible)
4711f5f7 79because it makes sub classing your class much easier.
e67a0fca 80
81If you need to affect the constructor's parameters prior to the
82instance actually being constructed, you have a number of options.
83
84First, there are I<coercions> (See the L<Moose::Cookbook::Recipe5>
85for a complete example and explaination of coercions). With
86coercions it is possible to morph argument values into the correct
87expected types. This approach is the most flexible and robust, but
88does have a slightly higher learning curve.
89
90Second, using an C<around> method modifier on C<new> can be an
91effective way to affect the contents of C<@_> prior to letting
92Moose deal with it. This carries with it the extra burden for
93your subclasses, in that they have to be sure to explicitly
94call your C<new> and/or work around your C<new> to get to the
95version from L<Moose::Object>.
96
97The last approach is to use the standard Perl technique of calling
807f6b7c 98the C<SUPER::new> within your own custom version of C<new>. This,
99of course, brings with it all the issues of the C<around> solution
100as well as any issues C<SUPER::> might add.
e67a0fca 101
102In short, try to use C<BUILD> and coercions, they are your best
103bets.
104
4711f5f7 105=head3 How do I make non-Moose constructors work with Moose?
e67a0fca 106
807f6b7c 107Moose provides its own constructor, but it does it by making all
e67a0fca 108Moose-based classes inherit from L<Moose::Object>. When inheriting
4711f5f7 109from a non-Moose class, the inheritance chain to L<Moose::Object>
e67a0fca 110is broken. The simplest way to fix this is to simply explicitly
111inherit from L<Moose::Object> yourself. However, this does not
112always fix the issue of a constructor. Here is a basic example of
113how this can be worked around:
114
115 package My::HTML::Template;
116 use Moose;
117
4711f5f7 118 # explicit inheritance
e67a0fca 119 extends 'HTML::Template', 'Moose::Object';
120
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__
129 __INSTANCE__ => $obj, @_
130 );
131 }
132
807f6b7c 133Of course, this only works if both your Moose class and the
e67a0fca 134inherited non-Moose class use the same instance type (typically
135HASH refs).
136
137Other techniques can be used as well, such as creating the object
138using C<Moose::Object::new>, but calling the inherited non-Moose
4711f5f7 139class's initialization methods (if available).
e67a0fca 140
807f6b7c 141It is also entirely possible to just rely on HASH autovivification
142to create the slots needed for Moose based attributes, although this
143does restrict use of construction time attribute features somewhat.
e67a0fca 144
145In short, there are several ways to go about this, it is best to
146evaluate each case based on the class you wish to extend, and the
147features you wish to employ. As always, both IRC and the mailing
148list are great ways to get help finding the best approach.
149
150=head2 Accessors
151
152=head3 How do I tell Moose to use get/set accessors?
153
154The easiest way to accomplish this is to use the C<reader> and
155C<writer> attribute options. Here is some example code:
156
157 has 'bar' => (
158 isa => 'Baz',
159 reader => 'get_bar',
160 writer => 'set_bar',
161 );
162
163Moose will still take advantage of type constraints, triggers, etc.
164when creating these methods.
165
807f6b7c 166If you do not like this much typing, and wish it to be a default for
167your class, please see L<Moose::Policy>, and more specifically
168L<Moose::Policy::FollowPBP>. This will allow you to write:
e67a0fca 169
170 has 'bar' => (
171 isa => 'Baz',
172 is => 'rw',
173 );
174
807f6b7c 175And have Moose create seperate C<get_bar> and C<set_bar> methods
176instead of a single C<bar> method.
e67a0fca 177
807f6b7c 178NOTE: This B<cannot> be set globally in Moose, as that would break
e67a0fca 179other classes which are built with Moose.
180
181=head3 How can I get Moose to inflate/deflate values in the accessor?
182
183Well, the first question to ask is if you actually need both inflate
184and deflate.
185
186If you only need to inflate, then I suggest using coercions. Here is
807f6b7c 187some basic sample code for inflating a L<DateTime> object:
e67a0fca 188
189 subtype 'DateTime'
190 => as 'Object'
191 => where { $_->isa('DateTime') };
192
193 coerce 'DateTime'
194 => from 'Str'
195 => via { DateTime::Format::MySQL->parse_datetime($_) };
196
197 has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
198
199This creates a custom subtype for L<DateTime> objects, then attaches
200a coercion to that subtype. The C<timestamp> attribute is then told
807f6b7c 201to expect a C<DateTime> type, and to try to coerce it. When a C<Str>
e67a0fca 202type is given to the C<timestamp> accessor, it will attempt to
203coerce the value into a C<DateTime> object using the code in found
204in the C<via> block.
205
807f6b7c 206For a more comprehensive example of using coercions, see the
e67a0fca 207L<Moose::Cookbook::Recipe5>.
208
209If you need to deflate your attribute, the current best practice is to
210add an C<around> modifier to your accessor. Here is some example code:
211
212 # a timestamp which stores as
213 # seconds from the epoch
214 has 'timestamp' => (is => 'rw', isa => 'Int');
215
216 around 'timestamp' => sub {
217 my $next = shift;
218 my ($self, $timestamp) = @_;
219 # assume we get a DateTime object ...
220 $next->($self, $timestamp->epoch);
221 };
222
223It is also possible to do deflation using coercion, but this tends
224to get quite complex and require many subtypes. An example of this
225is outside the scope of this document, ask on #moose or send a mail
226to the list.
227
228Still another option is to write a custom attribute metaclass, which
229is also outside the scope of this document, but I would be happy to
230explain it on #moose or the mailing list.
231
4711f5f7 232=head2 Method Modifiers
e67a0fca 233
234=head3 How can I affect the values in C<@_> using C<before>?
235
807f6b7c 236You can't, actually: C<before> only runs before the main method,
237and it cannot easily affect the method's execution. What you want is
e67a0fca 238an C<around> method.
239
240=head3 Can I use C<before> to stop execution of a method?
241
242Yes, but only if you throw an exception. If this is too drastic a
243measure then I suggest using C<around> instead. The C<around> method
807f6b7c 244modifier is the only modifier which can gracefully prevent execution
e67a0fca 245of the main method. Here is an example:
246
247 around 'baz' => sub {
248 my $next = shift;
249 my ($self, %options) = @_;
807f6b7c 250 unless ($options->{bar} eq 'foo') {
251 return 'bar';
e67a0fca 252 }
807f6b7c 253 $next->($self, %options);
e67a0fca 254 };
255
256By choosing not to call the C<$next> method, you can stop the
257execution of the main method.
258
259=head2 Type Constraints
260
261=head3 How can I have a custom error message for a type constraint?
262
807f6b7c 263Use the C<message> option when building the subtype, like so:
e67a0fca 264
265 subtype 'NaturalLessThanTen'
266 => as 'Natural'
267 => where { $_ < 10 }
268 => message { "This number ($_) is not less than ten!" };
269
270This will be called when a value fails to pass the C<NaturalLessThanTen>
271constraint check.
272
807f6b7c 273=head3 Can I turn off type constraint checking?
734d1752 274
275Not yet, but soon. This option will likely be coming in the next
276release.
277
b36c8076 278=head2 Roles
279
280=head3 How do I get Moose to call BUILD in all my composed roles?
281
282See L<Moose::Cookbook::WTF> and specifically the B<How come BUILD
283is not called for my composed roles?> question in the B<Roles> section.
284
e67a0fca 285=head1 AUTHOR
286
287Stevan Little E<lt>stevan@iinteractive.comE<gt>
288
289=head1 COPYRIGHT AND LICENSE
290
778db3ac 291Copyright 2006-2008 by Infinity Interactive, Inc.
e67a0fca 292
293L<http://www.iinteractive.com>
294
295This library is free software; you can redistribute it and/or modify
296it under the same terms as Perl itself.
297
298=cut