1Moose::Util::TypeConstrUasienrtsC(o3n)tributed Perl DocuMmoeonstea:t:iUotnil::TypeConstraints(3)
2
3
4
6 Moose::Util::TypeConstraints - Type constraint system for Moose
7
9 use Moose::Util::TypeConstraints;
10
11 subtype 'Natural'
12 => as 'Int'
13 => where { $_ > 0 };
14
15 subtype 'NaturalLessThanTen'
16 => as 'Natural'
17 => where { $_ < 10 }
18 => message { "This number ($_) is not less than ten!" };
19
20 coerce 'Num'
21 => from 'Str'
22 => via { 0+$_ };
23
24 enum 'RGBColors' => qw(red green blue);
25
26 no Moose::Util::TypeConstraints;
27
29 This module provides Moose with the ability to create custom type
30 constraints to be used in attribute definition.
31
32 Important Caveat
33 This is NOT a type system for Perl 5. These are type constraints, and
34 they are not used by Moose unless you tell it to. No type inference is
35 performed, expressions are not typed, etc. etc. etc.
36
37 A type constraint is at heart a small "check if a value is valid"
38 function. A constraint can be associated with an attribute. This
39 simplifies parameter validation, and makes your code clearer to read,
40 because you can refer to constraints by name.
41
42 Slightly Less Important Caveat
43 It is always a good idea to quote your type names.
44
45 This prevents Perl from trying to execute the call as an indirect
46 object call. This can be an issue when you have a subtype with the same
47 name as a valid class.
48
49 For instance:
50
51 subtype DateTime => as Object => where { $_->isa('DateTime') };
52
53 will just work, while this:
54
55 use DateTime;
56 subtype DateTime => as Object => where { $_->isa('DateTime') };
57
58 will fail silently and cause many headaches. The simple way to solve
59 this, as well as future proof your subtypes from classes which have yet
60 to have been created, is to quote the type name:
61
62 use DateTime;
63 subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };
64
65 Default Type Constraints
66 This module also provides a simple hierarchy for Perl 5 types, here is
67 that hierarchy represented visually.
68
69 Any
70 Item
71 Bool
72 Maybe[`a]
73 Undef
74 Defined
75 Value
76 Str
77 Num
78 Int
79 ClassName
80 RoleName
81 Ref
82 ScalarRef[`a]
83 ArrayRef[`a]
84 HashRef[`a]
85 CodeRef
86 RegexpRef
87 GlobRef
88 FileHandle
89 Object
90
91 NOTE: Any type followed by a type parameter "[`a]" can be
92 parameterized, this means you can say:
93
94 ArrayRef[Int] # an array of integers
95 HashRef[CodeRef] # a hash of str to CODE ref mappings
96 ScalarRef[Int] # a reference to an integer
97 Maybe[Str] # value may be a string, may be undefined
98
99 If Moose finds a name in brackets that it does not recognize as an
100 existing type, it assumes that this is a class name, for example
101 "ArrayRef[DateTime]".
102
103 NOTE: Unless you parameterize a type, then it is invalid to include the
104 square brackets. I.e. "ArrayRef[]" will be treated as a new type name,
105 not as a parameterization of "ArrayRef".
106
107 NOTE: The "Undef" type constraint for the most part works correctly
108 now, but edge cases may still exist, please use it sparingly.
109
110 NOTE: The "ClassName" type constraint does a complex package existence
111 check. This means that your class must be loaded for this type
112 constraint to pass.
113
114 NOTE: The "RoleName" constraint checks a string is a package name which
115 is a role, like 'MyApp::Role::Comparable'.
116
117 Type Constraint Naming
118 Type name declared via this module can only contain alphanumeric
119 characters, colons (:), and periods (.).
120
121 Since the types created by this module are global, it is suggested that
122 you namespace your types just as you would namespace your modules. So
123 instead of creating a Color type for your My::Graphics module, you
124 would call the type My::Graphics::Types::Color instead.
125
126 Use with Other Constraint Modules
127 This module can play nicely with other constraint modules with some
128 slight tweaking. The "where" clause in types is expected to be a "CODE"
129 reference which checks it's first argument and returns a boolean. Since
130 most constraint modules work in a similar way, it should be simple to
131 adapt them to work with Moose.
132
133 For instance, this is how you could use it with
134 Declare::Constraints::Simple to declare a completely new type.
135
136 type 'HashOfArrayOfObjects',
137 {
138 where => IsHashRef(
139 -keys => HasLength,
140 -values => IsArrayRef(IsObject)
141 )
142 };
143
144 For more examples see the t/200_examples/004_example_w_DCS.t test file.
145
146 Here is an example of using Test::Deep and it's non-test related
147 "eq_deeply" function.
148
149 type 'ArrayOfHashOfBarsAndRandomNumbers'
150 => where {
151 eq_deeply($_,
152 array_each(subhashof({
153 bar => isa('Bar'),
154 random_number => ignore()
155 })))
156 };
157
158 For a complete example see the t/200_examples/005_example_w_TestDeep.t
159 test file.
160
162 Type Constraint Constructors
163 The following functions are used to create type constraints. They will
164 also register the type constraints your create in a global registry
165 that is used to look types up by name.
166
167 See the "SYNOPSIS" for an example of how to use these.
168
169 subtype 'Name' => as 'Parent' => where { } ...
170 This creates a named subtype.
171
172 If you provide a parent that Moose does not recognize, it will
173 automatically create a new class type constraint for this name.
174
175 When creating a named type, the "subtype" function should either be
176 called with the sugar helpers ("where", "message", etc), or with a
177 name and a hashref of parameters:
178
179 subtype( 'Foo', { where => ..., message => ... } );
180
181 The valid hashref keys are "as" (the parent), "where", "message",
182 and "optimize_as".
183
184 subtype as 'Parent' => where { } ...
185 This creates an unnamed subtype and will return the type constraint
186 meta-object, which will be an instance of
187 Moose::Meta::TypeConstraint.
188
189 When creating an anonymous type, the "subtype" function should
190 either be called with the sugar helpers ("where", "message", etc),
191 or with just a hashref of parameters:
192
193 subtype( { where => ..., message => ... } );
194
195 class_type ($class, ?$options)
196 Creates a new subtype of "Object" with the name $class and the
197 metaclass Moose::Meta::TypeConstraint::Class.
198
199 role_type ($role, ?$options)
200 Creates a "Role" type constraint with the name $role and the
201 metaclass Moose::Meta::TypeConstraint::Role.
202
203 maybe_type ($type)
204 Creates a type constraint for either "undef" or something of the
205 given type.
206
207 duck_type ($name, \@methods)
208 This will create a subtype of Object and test to make sure the
209 value "can()" do the methods in "\@methods".
210
211 This is intended as an easy way to accept non-Moose objects that
212 provide a certain interface. If you're using Moose classes, we
213 recommend that you use a "requires"-only Role instead.
214
215 duck_type (\@methods)
216 If passed an ARRAY reference as the only parameter instead of the
217 $name, "\@methods" pair, this will create an unnamed duck type.
218 This can be used in an attribute definition like so:
219
220 has 'cache' => (
221 is => 'ro',
222 isa => duck_type( [qw( get_set )] ),
223 );
224
225 enum ($name, \@values)
226 This will create a basic subtype for a given set of strings. The
227 resulting constraint will be a subtype of "Str" and will match any
228 of the items in "\@values". It is case sensitive. See the
229 "SYNOPSIS" for a simple example.
230
231 NOTE: This is not a true proper enum type, it is simply a
232 convenient constraint builder.
233
234 enum (\@values)
235 If passed an ARRAY reference as the only parameter instead of the
236 $name, "\@values" pair, this will create an unnamed enum. This can
237 then be used in an attribute definition like so:
238
239 has 'sort_order' => (
240 is => 'ro',
241 isa => enum([qw[ ascending descending ]]),
242 );
243
244 as 'Parent'
245 This is just sugar for the type constraint construction syntax.
246
247 It takes a single argument, which is the name of a parent type.
248
249 where { ... }
250 This is just sugar for the type constraint construction syntax.
251
252 It takes a subroutine reference as an argument. When the type
253 constraint is tested, the reference is run with the value to be
254 tested in $_. This reference should return true or false to
255 indicate whether or not the constraint check passed.
256
257 message { ... }
258 This is just sugar for the type constraint construction syntax.
259
260 It takes a subroutine reference as an argument. When the type
261 constraint fails, then the code block is run with the value
262 provided in $_. This reference should return a string, which will
263 be used in the text of the exception thrown.
264
265 optimize_as { ... }
266 This can be used to define a "hand optimized" version of your type
267 constraint which can be used to avoid traversing a subtype
268 constraint hierarchy.
269
270 NOTE: You should only use this if you know what you are doing, all
271 the built in types use this, so your subtypes (assuming they are
272 shallow) will not likely need to use this.
273
274 type 'Name' => where { } ...
275 This creates a base type, which has no parent.
276
277 The "type" function should either be called with the sugar helpers
278 ("where", "message", etc), or with a name and a hashref of
279 parameters:
280
281 type( 'Foo', { where => ..., message => ... } );
282
283 The valid hashref keys are "where", "message", and "optimize_as".
284
285 Type Constraint Utilities
286 match_on_type $value => ( $type => \&action, ... ?\&default )
287 This is a utility function for doing simple type based dispatching
288 similar to match/case in OCaml and case/of in Haskell. It is not as
289 featureful as those languages, nor does not it support any kind of
290 automatic destructuring bind. Here is a simple Perl pretty printer
291 dispatching over the core Moose types.
292
293 sub ppprint {
294 my $x = shift;
295 match_on_type $x => (
296 HashRef => sub {
297 my $hash = shift;
298 '{ '
299 . (
300 join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
301 sort keys %$hash
302 ) . ' }';
303 },
304 ArrayRef => sub {
305 my $array = shift;
306 '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
307 },
308 CodeRef => sub {'sub { ... }'},
309 RegexpRef => sub { 'qr/' . $_ . '/' },
310 GlobRef => sub { '*' . B::svref_2object($_)->NAME },
311 Object => sub { $_->can('to_string') ? $_->to_string : $_ },
312 ScalarRef => sub { '\\' . ppprint( ${$_} ) },
313 Num => sub {$_},
314 Str => sub { '"' . $_ . '"' },
315 Undef => sub {'undef'},
316 => sub { die "I don't know what $_ is" }
317 );
318 }
319
320 Or a simple JSON serializer:
321
322 sub to_json {
323 my $x = shift;
324 match_on_type $x => (
325 HashRef => sub {
326 my $hash = shift;
327 '{ '
328 . (
329 join ", " =>
330 map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
331 sort keys %$hash
332 ) . ' }';
333 },
334 ArrayRef => sub {
335 my $array = shift;
336 '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
337 },
338 Num => sub {$_},
339 Str => sub { '"' . $_ . '"' },
340 Undef => sub {'null'},
341 => sub { die "$_ is not acceptable json type" }
342 );
343 }
344
345 The matcher is done by mapping a $type to an "\&action". The $type
346 can be either a string type or a Moose::Meta::TypeConstraint
347 object, and "\&action" is a subroutine reference. This function
348 will dispatch on the first match for $value. It is possible to have
349 a catch-all by providing an additional subroutine reference as the
350 final argument to "match_on_type".
351
352 Type Coercion Constructors
353 You can define coercions for type constraints, which allow you to
354 automatically transform values to something valid for the type
355 constraint. If you ask your accessor to coerce, then Moose will run the
356 type-coercion code first, followed by the type constraint check. This
357 feature should be used carefully as it is very powerful and could
358 easily take off a limb if you are not careful.
359
360 See the "SYNOPSIS" for an example of how to use these.
361
362 coerce 'Name' => from 'OtherName' => via { ... }
363 This defines a coercion from one type to another. The "Name"
364 argument is the type you are coercing to.
365
366 from 'OtherName'
367 This is just sugar for the type coercion construction syntax.
368
369 It takes a single type name (or type object), which is the type
370 being coerced from.
371
372 via { ... }
373 This is just sugar for the type coercion construction syntax.
374
375 It takes a subroutine reference. This reference will be called with
376 the value to be coerced in $_. It is expected to return a new value
377 of the proper type for the coercion.
378
379 Creating and Finding Type Constraints
380 These are additional functions for creating and finding type
381 constraints. Most of these functions are not available for importing.
382 The ones that are importable as specified.
383
384 find_type_constraint($type_name)
385 This function can be used to locate the Moose::Meta::TypeConstraint
386 object for a named type.
387
388 This function is importable.
389
390 register_type_constraint($type_object)
391 This function will register a Moose::Meta::TypeConstraint with the
392 global type registry.
393
394 This function is importable.
395
396 normalize_type_constraint_name($type_constraint_name)
397 This method takes a type constraint name and returns the normalized
398 form. This removes any whitespace in the string.
399
400 create_type_constraint_union($pipe_separated_types |
401 @type_constraint_names)
402 This can take a union type specification like 'Int|ArrayRef[Int]',
403 or a list of names. It returns a new
404 Moose::Meta::TypeConstraint::Union object.
405
406 create_parameterized_type_constraint($type_name)
407 Given a $type_name in the form of 'BaseType[ContainerType]', this
408 will create a new Moose::Meta::TypeConstraint::Parameterized
409 object. The "BaseType" must exist already exist as a
410 parameterizable type.
411
412 create_class_type_constraint($class, $options)
413 Given a class name this function will create a new
414 Moose::Meta::TypeConstraint::Class object for that class name.
415
416 The $options is a hash reference that will be passed to the
417 Moose::Meta::TypeConstraint::Class constructor (as a hash).
418
419 create_role_type_constraint($role, $options)
420 Given a role name this function will create a new
421 Moose::Meta::TypeConstraint::Role object for that role name.
422
423 The $options is a hash reference that will be passed to the
424 Moose::Meta::TypeConstraint::Role constructor (as a hash).
425
426 create_enum_type_constraint($name, $values)
427 Given a enum name this function will create a new
428 Moose::Meta::TypeConstraint::Enum object for that enum name.
429
430 create_duck_type_constraint($name, $methods)
431 Given a duck type name this function will create a new
432 Moose::Meta::TypeConstraint::DuckType object for that enum name.
433
434 find_or_parse_type_constraint($type_name)
435 Given a type name, this first attempts to find a matching
436 constraint in the global registry.
437
438 If the type name is a union or parameterized type, it will create a
439 new object of the appropriate, but if given a "regular" type that
440 does not yet exist, it simply returns false.
441
442 When given a union or parameterized type, the member or base type
443 must already exist.
444
445 If it creates a new union or parameterized type, it will add it to
446 the global registry.
447
448 find_or_create_isa_type_constraint($type_name)
449 find_or_create_does_type_constraint($type_name)
450 These functions will first call "find_or_parse_type_constraint". If
451 that function does not return a type, a new anonymous type object
452 will be created.
453
454 The "isa" variant will use "create_class_type_constraint" and the
455 "does" variant will use "create_role_type_constraint".
456
457 get_type_constraint_registry
458 Returns the Moose::Meta::TypeConstraint::Registry object which
459 keeps track of all type constraints.
460
461 list_all_type_constraints
462 This will return a list of type constraint names in the global
463 registry. You can then fetch the actual type object using
464 "find_type_constraint($type_name)".
465
466 list_all_builtin_type_constraints
467 This will return a list of builtin type constraints, meaning those
468 which are defined in this module. See the "Default Type
469 Constraints" section for a complete list.
470
471 export_type_constraints_as_functions
472 This will export all the current type constraints as functions into
473 the caller's namespace ("Int()", "Str()", etc). Right now, this is
474 mostly used for testing, but it might prove useful to others.
475
476 get_all_parameterizable_types
477 This returns all the parameterizable types that have been
478 registered, as a list of type objects.
479
480 add_parameterizable_type($type)
481 Adds $type to the list of parameterizable types
482
484 See "BUGS" in Moose for details on reporting bugs.
485
487 Stevan Little <stevan@iinteractive.com>
488
490 Copyright 2006-2010 by Infinity Interactive, Inc.
491
492 <http://www.iinteractive.com>
493
494 This library is free software; you can redistribute it and/or modify it
495 under the same terms as Perl itself.
496
497
498
499perl v5.12.2 2010-08-28 Moose::Util::TypeConstraints(3)