5 Moose::Manual::Types - Moose's type system
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
13 Moose's type system is based on a combination of Perl 5's own
14 I<implicit> types and some Perl 6 concepts. You can create your
15 own subtypes with custom constraints, making it easy to express any
18 Types have names, and you can re-use them by name, making it easy to
19 share types throughout a large application.
21 However, this is not a "real" type system. Moose does not magically make Perl
22 start associating types with variables. This is just an advanced parameter
23 checking system which allows you to associate a name with a constraint.
25 That said, it's still pretty damn useful, and we think it's one of the
26 things that makes Moose both fun and powerful. Taking advantage of the
27 type system makes it much easier to ensure that you are getting valid
28 data, and it also contributes greatly to code maintainability.
32 The basic Moose type hierarchy looks like this
56 In practice, the only difference between C<Any> and C<Item> is
57 conceptual. C<Item> is used as the top-level type in the hierarchy.
59 The rest of these types correspond to existing Perl concepts.
66 C<Bool> accepts C<1> for true, and undef, 0, or the empty string as false.
70 C<Maybe[`a]> accepts either C<`a> or C<undef>.
74 C<Num> accepts anything that perl thinks looks like a number (see L<Scalar::Util/looks_like_number>).
78 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 already be loaded when the constraint is checked.
82 C<FileHandle> accepts either an L<IO::Handle> object or a builtin perl filehandle (see L<Scalar::Util/openhandle>).
86 C<Object> accepts any blessed reference.
90 The types followed by "[`a]" can be parameterized. So instead of just
91 plain C<ArrayRef> we can say that we want C<ArrayRef[Int]> instead. We
92 can even do something like C<HashRef[ArrayRef[Str]]>.
94 The C<Maybe[`a]> type deserves a special mention. Used by itself, it
95 doesn't really mean anything (and is equivalent to C<Item>). When it
96 is parameterized, it means that the value is either C<undef> or the
97 parameterized type. So C<Maybe[Int]> means an integer or C<undef>.
99 For more details on the type hierarchy, see
100 L<Moose::Util::TypeConstraints>.
102 =head1 WHAT IS A TYPE?
104 It's important to realize that types are not classes (or
105 packages). Types are just objects (L<Moose::Meta::TypeConstraint>
106 objects, to be exact) with a name and a constraint. Moose maintains a
107 global type registry that lets it convert names like C<Num> into the
110 However, class names I<can be> type names. When you define a new class
111 using Moose, it defines an associated type name behind the scenes:
117 Now you can use C<'MyApp::User'> as a type name:
121 isa => 'MyApp::User',
124 However, for non-Moose classes there's no magic. You may have to
125 explicitly declare the class type. This is a bit muddled because Moose
126 assumes that any unknown type name passed as the C<isa> value for an
127 attribute is a class. So this works:
129 has 'birth_date' => (
134 In general, when Moose is presented with an unknown name, it assumes
135 that the name is a class:
137 subtype 'ModernDateTime'
139 => where { $_->year() >= 1980 }
140 => message { 'The date you provided is not modern enough' };
142 has 'valid_dates' => (
144 isa => 'ArrayRef[DateTime]',
147 Moose will assume that C<DateTime> is a class name in both of these
152 Moose uses subtypes in its built-in hierarchy. For example, C<Int> is
155 A subtype is defined in terms of a parent type and a constraint. Any
156 constraints defined by the parent(s) will be checked first, followed by
157 constraints defined by the subtype. A value must pass I<all> of these
158 checks to be valid for the subtype.
160 Typically, a subtype takes the parent's constraint and makes it more
163 A subtype can also define its own constraint failure message. This
164 lets you do things like have an error "The value you provided (20),
165 was not a valid rating, which must be a number from 1-10." This is
166 much friendlier than the default error, which just says that the value
167 failed a validation check for the type.
169 Here's a simple (and useful) subtype example:
171 subtype 'PositiveInt'
174 => message { "The number you provided, $_, was not a positive number" }
176 Note that the sugar functions for working with types are all exported
177 by L<Moose::Util::TypeConstraints>.
181 Type names are global throughout the current Perl
182 interpreter. Internally, Moose maps names to type objects via a
183 L<registry|Moose::Meta::TypeConstraint::Registry>.
185 If you have multiple apps or libraries all using Moose in the same
186 process, you could have problems with collisions. We recommend that
187 you prefix names with some sort of namespace indicator to prevent
188 these sorts of collisions.
190 For example, instead of calling a type "PositiveInt", call it
191 "MyApp::Type::PositiveInt" or "MyApp::Types::PositiveInt". We
192 recommend that you centralize all of these definitions in a single
193 package, C<MyApp::Types>, which can be loaded by other classes in your
196 However, before you do this, you should look at the L<MooseX::Types>
197 module. This module makes it easy to create a "type library" module, which can
198 export your types as perl constants.
200 has 'counter' => (is => 'rw', isa => PositiveInt);
202 This lets you use a short name rather than needing to fully qualify the name
203 everywhere. It also allows you to write easily create parameterized types:
205 has 'counts' => (is => 'ro', isa => HashRef[PositiveInt]);
207 This module will check your names at compile time, and is generally more
208 robust than the string type parsing for complex cases.
212 A coercion lets you tell Moose to automatically convert one type to another.
214 subtype 'ArrayRefOfInts'
215 => as 'ArrayRef[Int]';
217 coerce 'ArrayRefOfInts'
221 You'll note that we created a subtype rather than coercing C<ArrayRef[Int]>
222 directly. It's a bad idea to add coercions to the raw built in
225 Coercions are global, just like type names, so a coercion applied to a built
226 in type is seen by all modules using Moose types. This is I<another> reason
227 why it is good to namespace your types.
229 Moose will I<never> try to coerce a value unless you explicitly ask for
230 it. This is done by setting the C<coerce> attribute option to a true value:
236 isa => 'ArrayRefOfInts',
240 Foo->new( sizes => 42 );
242 This code example will do the right thing, and the newly created
243 object will have C<[ 42 ]> as its C<sizes> attribute.
247 Deep coercion is the coercion of type parameters for parameterized
248 types. Let's take these types as an example:
252 => where { /[a-f0-9]/i };
260 isa => 'ArrayRef[Int]',
264 If we try passing an array reference of hex numbers for the C<sizes>
265 attribute, Moose will not do any coercion.
267 However, you can define a set of subtypes to enable coercion between
268 two parameterized types.
270 subtype 'ArrayRefOfHexNums'
271 => as 'ArrayRef[HexNum]';
273 subtype 'ArrayRefOfInts'
274 => as 'ArrayRef[Int]';
276 coerce 'ArrayRefOfInts'
277 => from 'ArrayRefOfHexNums'
278 => via { [ map { hex } @{$_} ] };
280 Foo->new( sizes => [ 'a1', 'ff', '22' ] );
282 Now Moose will coerce the hex numbers to integers.
284 Moose does not attempt to chain coercions, so it will not
285 coerce a single hex number. To do that, we need to define a separate
288 coerce 'ArrayRefOfInts'
290 => via { [ hex $_ ] };
292 Yes, this can all get verbose, but coercion is tricky magic, and we
293 think it's best to make it explicit.
297 Moose allows you to say that an attribute can be of two or more
298 disparate types. For example, we might allow an C<Object> or
303 isa => 'Object | FileHandle',
306 Moose actually parses that string and recognizes that you are creating
307 a type union. The C<output> attribute will accept any sort of object,
308 as well as an unblessed file handle. It is up to you to do the right
309 thing for each of them in your code.
311 Whenever you use a type union, you should consider whether or not
312 coercion might be a better answer.
314 For our example above, we might want to be more specific, and insist
315 that output be an object with a C<print> method:
319 => where { $_->can('print') };
321 We can coerce file handles to an object that satisfies this condition
322 with a simple wrapper class:
335 my $fh = $self->handle();
340 Now we can define a coercion from C<FileHandle> to our wrapper class:
344 => via { FHWrapper->new( handle => $_ ) };
352 This pattern of using a coercion instead of a type union will help
353 make your class internals simpler.
355 =head1 TYPE CREATION HELPERS
357 The L<Moose::Util::TypeConstraints> module exports a number of helper
358 functions for creating specific kinds of types. These include
359 C<class_type>, C<role_type>, and C<maybe_type>. See the docs for
362 One helper worth noting is C<enum>, which allows you to create a
363 subtype of C<Str> that only allows the specified values:
365 enum 'RGB' => qw( red green blue );
367 This creates a type named C<RGB>.
369 =head1 ANONYMOUS TYPES
371 All of the type creation functions return a type object. This type
372 object can be used wherever you would use a type name, as a parent
373 type, or as the value for an attribute's C<isa> option:
377 isa => subtype( 'Int' => where { $_ > 0 } ),
380 This is handy when you want to create a one-off type and don't want to
381 "pollute" the global namespace registry.
383 =head1 VALIDATING METHOD PARAMETERS
385 Moose does not provide any means of validating method
386 parameters. However, there are several MooseX extensions on CPAN which
389 The simplest and least sugary is L<MooseX::Params::Validate>. This
390 lets you validate a set of named parameters using Moose types:
393 use MooseX::Params::Validate;
397 my %params = validated_hash(
399 bar => { isa => 'Str', default => 'Moose' },
404 L<MooseX::Params::Validate> also supports coercions.
406 There are several more powerful extensions that support method
407 parameter validation using Moose types, including
408 L<MooseX::Method::Signatures>, which gives you a full-blown C<method>
411 method morning ( Str $name ) {
412 $self->say("Good morning ${name}!");
415 =head1 LOAD ORDER ISSUES
417 Because Moose types are defined at runtime, you may run into load
418 order problems. In particular, you may want to use a class's type
419 constraint before that type has been defined.
421 In order to ameliorate this problem, we recommend defining I<all> of your
422 custom types in one module, C<MyApp::Types>, and then loading this module in
423 all of your other modules.
427 Dave Rolsky E<lt>autarch@urth.orgE<gt>
429 =head1 COPYRIGHT AND LICENSE
431 Copyright 2009-2010 by Infinity Interactive, Inc.
433 L<http://www.iinteractive.com>
435 This library is free software; you can redistribute it and/or modify
436 it under the same terms as Perl itself.