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