Commit | Line | Data |
ecd7cc3e |
1 | =pod |
2 | |
3 | =head1 NAME |
4 | |
d67ce58f |
5 | Moose::Manual::Types - Moose's type system |
ecd7cc3e |
6 | |
7 | =head1 TYPES IN PERL? |
8 | |
0c551c67 |
9 | Moose provides its own type system for attributes. You can also use |
10 | these types to validate method parameters with the help of a MooseX |
11 | module. |
ecd7cc3e |
12 | |
13 | Moose's type system is based on a combination of Perl 5's own |
0c551c67 |
14 | I<implicit> types and some Perl 6 concepts. You can easily create your |
15 | own subtypes with custom constraints, making it easy to express any |
16 | sort of validation. |
ecd7cc3e |
17 | |
0c551c67 |
18 | Types have names, and you can re-use them by name, making it easy to |
ecd7cc3e |
19 | share types throughout a large application. |
20 | |
21 | Let us be clear that is not a "real" type system. Moose does not |
0c551c67 |
22 | magically make Perl start associating types with variables. This is |
23 | just an advanced parameter checking system which allows you to |
24 | associate a name with a constraint. |
ecd7cc3e |
25 | |
26 | That said, it's still pretty damn useful, and we think it's one of the |
27 | things that makes Moose both fun and powerful. Taking advantage of the |
28 | type system makes it much easier to ensure that you are getting valid |
29 | data, and it also contributes greatly to code maintainability. |
30 | |
31 | =head1 THE TYPES |
32 | |
33 | The basic Moose type hierarchy looks like this |
34 | |
35 | Any |
36 | Item |
37 | Bool |
38 | Maybe[`a] |
39 | Undef |
40 | Defined |
41 | Value |
ecd7cc3e |
42 | Str |
f1bbe1e1 |
43 | Num |
44 | Int |
ecd7cc3e |
45 | ClassName |
7612cc01 |
46 | RoleName |
ecd7cc3e |
47 | Ref |
977a5e90 |
48 | ScalarRef[`a] |
ecd7cc3e |
49 | ArrayRef[`a] |
50 | HashRef[`a] |
51 | CodeRef |
52 | RegexpRef |
53 | GlobRef |
54 | FileHandle |
55 | Object |
ecd7cc3e |
56 | |
57 | In practice, the only difference between C<Any> and C<Item> is |
58 | conceptual. C<Item> is used as the top-level type in the hierarchy. |
59 | |
f91b2a92 |
60 | The rest of these types correspond to existing Perl concepts. |
61 | In particular: |
62 | |
63 | =over 4 |
64 | |
65 | =item C<Bool> accepts C<1> for true, and any value that perl treats as false for false. |
66 | |
67 | =item C<Maybe[`a]> accepts either C<`a> or C<undef>. |
68 | |
69 | =item C<Num> accepts anything that perl thinks looks like a number (see L<Scalar::Util/looks_like_number>). |
70 | |
76127c77 |
71 | =item C<ClassName> and C<RoleName> accept strings that are either the name of a class or the name of a role. The class/role must be loaded beforehand for this to succeed. |
f91b2a92 |
72 | |
73 | =item C<FileHandle> accepts either an object of type L<IO::Handle> or a builtin perl filehandle (see L<Scalar::Util/openhandle>). |
74 | |
75 | =item C<Object> accepts any blessed reference. |
76 | |
77 | =back |
ecd7cc3e |
78 | |
79 | The types followed by "[`a]" can be parameterized. So instead of just |
80 | plain C<ArrayRef> we can say that we want C<ArrayRef[Int]> instead. We |
81 | can even do something like C<HashRef[ArrayRef[Str]]>. |
82 | |
83 | The C<Maybe[`a]> type deserves a special mention. Used by itself, it |
84 | doesn't really mean anything (and is equivalent to C<Item>). When it |
85 | is parameterized, it means that the value is either C<undef> or the |
5a3fb5fc |
86 | parameterized type. So C<Maybe[Int]> means an integer or C<undef>. |
ecd7cc3e |
87 | |
88 | For more details on the type hierarchy, see |
89 | L<Moose::Util::TypeConstraints>. |
90 | |
91 | =head1 WHAT IS A TYPE? |
92 | |
93 | It's important to realize that types are not classes (or |
94 | packages). Types are just objects (L<Moose::Meta::TypeConstraint> |
0c551c67 |
95 | objects, to be exact) with a name and a constraint. Moose maintains a |
6549b0d1 |
96 | global type registry that lets it convert names like C<Num> into the |
0c551c67 |
97 | appropriate object. |
ecd7cc3e |
98 | |
99 | However, class names I<can be> type names. When you define a new class |
100 | using Moose, it defines an associated type name behind the scenes: |
101 | |
102 | package MyApp::User; |
103 | |
104 | use Moose; |
105 | |
106 | Now you can use C<'MyApp::User'> as a type name: |
107 | |
108 | has creator => ( |
6c5b976f |
109 | is => 'ro', |
ecd7cc3e |
110 | isa => 'MyApp::User', |
111 | ); |
112 | |
113 | However, for non-Moose classes there's no magic. You may have to |
114 | explicitly declare the class type. This is a bit muddled because Moose |
115 | assumes that any unknown type name passed as the C<isa> value for an |
116 | attribute is a class. So this works: |
117 | |
118 | has 'birth_date' => ( |
6c5b976f |
119 | is => 'ro', |
ecd7cc3e |
120 | isa => 'DateTime', |
121 | ); |
122 | |
123 | In general, when Moose is presented with an unknown name, it assumes |
124 | that the name is a class: |
125 | |
126 | subtype 'ModernDateTime' |
127 | => as 'DateTime' |
128 | => where { $_->year() >= 1980 } |
129 | => message { 'The date you provided is not modern enough' }; |
130 | |
131 | has 'valid_dates' => ( |
132 | is => 'ro', |
133 | isa => 'ArrayRef[DateTime]', |
134 | ); |
135 | |
0c39debe |
136 | Moose will assume that C<DateTime> is a class name in both of these |
0c551c67 |
137 | instances. |
ecd7cc3e |
138 | |
139 | =head1 SUBTYPES |
140 | |
dab94063 |
141 | Moose uses subtypes in its built-in hierarchy. For example, C<Int> is |
142 | a child of C<Num>. |
ecd7cc3e |
143 | |
144 | A subtype is defined in terms of a parent type and a constraint. Any |
dab94063 |
145 | constraints defined by the parent(s) will be checked first, followed by |
146 | constraints defined by the subtype. A value must pass I<all> of these |
147 | checks to be valid for the subtype. |
ecd7cc3e |
148 | |
0c551c67 |
149 | Typically, a subtype takes the parent's constraint and makes it more |
ecd7cc3e |
150 | specific. |
151 | |
152 | A subtype can also define its own constraint failure message. This |
153 | lets you do things like have an error "The value you provided (20), |
154 | was not a valid rating, which must be a number from 1-10." This is |
155 | much friendlier than the default error, which just says that the value |
156 | failed a validation check for the type. |
157 | |
158 | Here's a simple (and useful) subtype example: |
159 | |
160 | subtype 'PositiveInt' |
161 | => as 'Int' |
162 | => where { $_ > 0 } |
163 | => message { "The number you provided, $_, was not a positive number" } |
164 | |
165 | Note that the sugar functions for working with types are all exported |
166 | by L<Moose::Util::TypeConstraints>. |
167 | |
d67ce58f |
168 | =head2 Creating a new type (that isn't a subtype) |
ecd7cc3e |
169 | |
170 | You can also create new top-level types: |
171 | |
172 | type 'FourCharacters' => where { defined $_ && length $_ == 4 }; |
173 | |
0c551c67 |
174 | In practice, this example is more or less the same as subtyping |
636f25f3 |
175 | C<Str>, except you have to check definedness yourself. |
ecd7cc3e |
176 | |
177 | It's hard to find a case where you wouldn't want to subtype a very |
178 | broad type like C<Defined>, C<Ref> or C<Object>. |
179 | |
0c551c67 |
180 | Defining a new top-level type is conceptually the same as subtyping |
181 | C<Item>. |
ecd7cc3e |
182 | |
183 | =head1 TYPE NAMES |
184 | |
185 | Type names are global throughout the current Perl |
0c551c67 |
186 | interpreter. Internally, Moose maps names to type objects via a |
187 | L<registry|Moose::Meta::TypeConstraint::Registry>. |
ecd7cc3e |
188 | |
189 | If you have multiple apps or libraries all using Moose in the same |
190 | process, you could have problems with collisions. We recommend that |
191 | you prefix names with some sort of namespace indicator to prevent |
192 | these sorts of collisions. |
193 | |
194 | For example, instead of calling a type "PositiveInt", call it |
bcc22289 |
195 | "MyApp::Type::PositiveInt" or "MyApp::Types::PositiveInt". We |
196 | recommend that you centralize all of these definitions in a single |
197 | package, C<MyApp::Types>, which can be loaded by other classes in your |
198 | application. |
ecd7cc3e |
199 | |
06712014 |
200 | Once you're doing this, you should almost certainly look at the |
99f1bb40 |
201 | L<MooseX::Types> module. This module makes it easy to create a "type library" |
202 | module, which can export your types as perl constants. |
06712014 |
203 | |
204 | has 'counter' => (is => 'rw', isa => PositiveInt); |
205 | |
99f1bb40 |
206 | This lets you use a short name rather than needing to fully qualify the name |
207 | everywhere. It also allows you to write easily create parameterized types: |
06712014 |
208 | |
209 | has 'counts' => (is => 'ro', isa => HashRef[PositiveInt]); |
210 | |
99f1bb40 |
211 | This module will check your names at compile time, and is generally more |
212 | robust than the string type parsing for complex cases. |
06712014 |
213 | |
ecd7cc3e |
214 | =head1 COERCION |
215 | |
216 | One of the most powerful features of Moose's type system is its |
0c551c67 |
217 | coercions. A coercion is a way to convert from one type to another. |
ecd7cc3e |
218 | |
219 | subtype 'ArrayRefOfInts' |
220 | => as 'ArrayRef[Int]'; |
221 | |
222 | coerce 'ArrayRefOfInts' |
223 | => from 'Int' |
224 | => via { [ $_ ] }; |
225 | |
226 | You'll note that we had to create a subtype rather than coercing |
227 | C<ArrayRef[Int]> directly. This is just a quirk of how Moose |
228 | works. |
229 | |
230 | Coercions, like type names, are global. This is I<another> reason why |
231 | it is good to namespace your types. Moose will I<never> try to coerce |
232 | a value unless you explicitly ask for it. This is done by setting the |
16fb3624 |
233 | C<coerce> attribute option to a true value: |
ecd7cc3e |
234 | |
235 | package Foo; |
236 | |
237 | has 'sizes' => ( |
6c5b976f |
238 | is => 'ro', |
ecd7cc3e |
239 | isa => 'ArrayRefOfInts', |
240 | coerce => 1, |
241 | ); |
242 | |
243 | Foo->new( sizes => 42 ); |
244 | |
245 | This code example will do the right thing, and the newly created |
246 | object will have C<[ 42 ]> as its C<sizes> attribute. |
247 | |
d67ce58f |
248 | =head2 Deep coercion |
ecd7cc3e |
249 | |
250 | Deep coercion is the coercion of type parameters for parameterized |
251 | types. Let's take these types as an example: |
252 | |
253 | subtype 'HexNum' |
254 | => as 'Str' |
255 | => where { /[a-f0-9]/i }; |
256 | |
257 | coerce 'Int' |
258 | => from 'HexNum' |
259 | => via { hex $_ }; |
260 | |
261 | has 'sizes' => ( |
6c5b976f |
262 | is => 'ro', |
ecd7cc3e |
263 | isa => 'ArrayRef[Int]', |
264 | coerce => 1, |
265 | ); |
266 | |
267 | If we try passing an array reference of hex numbers for the C<sizes> |
0c551c67 |
268 | attribute, Moose will not do any coercion. |
ecd7cc3e |
269 | |
0c551c67 |
270 | However, you can define a set of subtypes to enable coercion between |
271 | two parameterized types. |
ecd7cc3e |
272 | |
273 | subtype 'ArrayRefOfHexNums' |
274 | => as 'ArrayRef[HexNum]'; |
275 | |
276 | subtype 'ArrayRefOfInts' |
277 | => as 'ArrayRef[Int]'; |
278 | |
279 | coerce 'ArrayRefOfInts' |
280 | => from 'ArrayRefOfHexNums' |
281 | => via { [ map { hex } @{$_} ] }; |
282 | |
283 | Foo->new( sizes => [ 'a1', 'ff', '22' ] ); |
284 | |
285 | Now Moose will coerce the hex numbers to integers. |
286 | |
0c551c67 |
287 | However, Moose does not attempt to chain coercions, so it will not |
288 | coerce a single hex number. To do that, we need to define a separate |
289 | coercion: |
ecd7cc3e |
290 | |
291 | coerce 'ArrayRefOfInts' |
292 | => from 'HexNum' |
293 | => via { [ hex $_ ] }; |
294 | |
295 | Yes, this can all get verbose, but coercion is tricky magic, and we |
0c551c67 |
296 | think it's best to make it explicit. |
ecd7cc3e |
297 | |
298 | =head1 TYPE UNIONS |
299 | |
300 | Moose allows you to say that an attribute can be of two or more |
301 | disparate types. For example, we might allow an C<Object> or |
302 | C<FileHandle>: |
303 | |
304 | has 'output' => ( |
305 | is => 'rw', |
306 | isa => 'Object | FileHandle', |
307 | ); |
308 | |
309 | Moose actually parses that string and recognizes that you are creating |
310 | a type union. The C<output> attribute will accept any sort of object, |
311 | as well as an unblessed file handle. It is up to you to do the right |
312 | thing for each of them in your code. |
313 | |
0c551c67 |
314 | Whenever you use a type union, you should consider whether or not |
315 | coercion might be a better answer. |
ecd7cc3e |
316 | |
317 | For our example above, we might want to be more specific, and insist |
318 | that output be an object with a C<print> method: |
319 | |
320 | subtype 'CanPrint' |
321 | => as 'Object' |
322 | => where { $_->can('print') }; |
323 | |
324 | We can coerce file handles to an object that satisfies this condition |
325 | with a simple wrapper class: |
326 | |
327 | package FHWrapper; |
328 | |
329 | use Moose; |
330 | |
331 | has 'handle' => ( |
6c5b976f |
332 | is => 'rw', |
ecd7cc3e |
333 | isa => 'FileHandle', |
334 | ); |
335 | |
336 | sub print { |
337 | my $self = shift; |
338 | my $fh = $self->handle(); |
339 | |
340 | print $fh @_; |
341 | } |
342 | |
343 | Now we can define a coercion from C<FileHandle> to our wrapper class: |
344 | |
0c551c67 |
345 | coerce 'CanPrint' |
ecd7cc3e |
346 | => from 'FileHandle' |
347 | => via { FHWrapper->new( handle => $_ ) }; |
348 | |
349 | has 'output' => ( |
350 | is => 'rw', |
351 | isa => 'CanPrint', |
352 | coerce => 1, |
353 | ); |
354 | |
0c551c67 |
355 | This pattern of using a coercion instead of a type union will help |
356 | make your class internals simpler. |
ecd7cc3e |
357 | |
358 | =head1 TYPE CREATION HELPERS |
359 | |
360 | The L<Moose::Util::TypeConstraints> module exports a number of helper |
361 | functions for creating specific kinds of types. These include |
362 | C<class_type>, C<role_type>, and C<maybe_type>. See the docs for |
363 | details. |
364 | |
365 | One helper worth noting is C<enum>, which allows you to create a |
366 | subtype of C<Str> that only allows the specified values: |
367 | |
368 | enum 'RGB' => qw( red green blue ); |
369 | |
dab94063 |
370 | This creates a type named C<RGB>. |
ecd7cc3e |
371 | |
372 | =head1 ANONYMOUS TYPES |
373 | |
374 | All of the type creation functions return a type object. This type |
375 | object can be used wherever you would use a type name, as a parent |
16fb3624 |
376 | type, or as the value for an attribute's C<isa> option: |
ecd7cc3e |
377 | |
378 | has 'size' => ( |
6c5b976f |
379 | is => 'ro', |
940ed284 |
380 | isa => subtype('Int' => where { $_ > 0 }), |
ecd7cc3e |
381 | ); |
382 | |
383 | This is handy when you want to create a one-off type and don't want to |
384 | "pollute" the global namespace registry. |
385 | |
386 | =head1 VALIDATING METHOD PARAMETERS |
387 | |
388 | Moose does not provide any means of validating method |
389 | parameters. However, there are several MooseX extensions on CPAN which |
390 | let you do this. |
391 | |
0c39debe |
392 | The simplest and least sugary is L<MooseX::Params::Validate>. This |
ecd7cc3e |
393 | lets you validate a set of named parameters using Moose types: |
394 | |
395 | use Moose; |
396 | use MooseX::Params::Validate; |
397 | |
398 | sub foo { |
399 | my $self = shift; |
0c551c67 |
400 | my %params = validated_hash( |
ecd7cc3e |
401 | \@_, |
402 | bar => { isa => 'Str', default => 'Moose' }, |
403 | ); |
404 | ... |
405 | } |
406 | |
0c39debe |
407 | L<MooseX::Params::Validate> also supports coercions. |
ecd7cc3e |
408 | |
409 | There are several more powerful extensions that support method |
410 | parameter validation using Moose types, including |
0c39debe |
411 | L<MooseX::Method::Signatures>, which gives you a full-blown C<method> |
ecd7cc3e |
412 | keyword. |
413 | |
414 | method morning (Str $name) { |
415 | $self->say("Good morning ${name}!"); |
416 | } |
417 | |
ca680d1f |
418 | =head1 LOAD ORDER ISSUES |
419 | |
0c551c67 |
420 | Because Moose types are defined at runtime, you may run into load |
421 | order problems. In particular, you may want to use a class's type |
422 | constraint before that type has been defined. |
ca680d1f |
423 | |
0c551c67 |
424 | We have several recommendations for ameliorating this problem. First, |
425 | define I<all> of your custom types in one module, |
426 | C<MyApp::Types>. Second, load this module in all of your other |
427 | modules. |
ca680d1f |
428 | |
ecd7cc3e |
429 | =head1 AUTHOR |
430 | |
431 | Dave Rolsky E<lt>autarch@urth.orgE<gt> |
432 | |
433 | =head1 COPYRIGHT AND LICENSE |
434 | |
2840a3b2 |
435 | Copyright 2009 by Infinity Interactive, Inc. |
ecd7cc3e |
436 | |
437 | L<http://www.iinteractive.com> |
438 | |
439 | This library is free software; you can redistribute it and/or modify |
440 | it under the same terms as Perl itself. |
441 | |
442 | =cut |