4 # ABSTRACT: Organise your Moose types in libraries
6 use Moose::Util::TypeConstraints;
7 use MooseX::Types::TypeDecorator;
8 use MooseX::Types::Base ();
9 use MooseX::Types::Util qw( filter_tags );
10 use MooseX::Types::UndefinedType;
11 use MooseX::Types::CheckedUtilExports ();
12 use Carp::Clan qw( ^MooseX::Types );
14 use Scalar::Util 'reftype';
16 use namespace::clean -except => [qw( meta )];
19 my $UndefMsg = q{Action for type '%s' not yet defined in library '%s'};
23 =head2 Library Definition
27 # predeclare our own types
28 use MooseX::Types -declare => [
33 ArrayRefOfAtLeastThreeNegativeInts
34 LotsOfInnerConstraints
40 # import builtin types
41 use MooseX::Types::Moose qw/Int HashRef/;
47 message { "Int is not larger than 0" };
52 message { "Int is not smaller than 0" };
59 # with parameterized constraints.
61 subtype ArrayRefOfPositiveInt,
62 as ArrayRef[PositiveInt];
64 subtype ArrayRefOfAtLeastThreeNegativeInts,
65 as ArrayRef[NegativeInt],
66 where { scalar(@$_) > 2 };
68 subtype LotsOfInnerConstraints,
69 as ArrayRef[ArrayRef[HashRef[Int]]];
71 # with TypeConstraint Unions
73 subtype StrOrArrayRef,
78 class_type 'DateTime';
82 class_type MyDateTime, { class => 'DateTime' };
86 via { DateTime->new(%$_) };
94 use MyLibrary qw( PositiveInt NegativeInt );
96 # use the exported constants as type names
108 print "positive\n" if is_PositiveInt($value);
109 print "negative\n" if is_NegativeInt($value);
111 # coerce the value, NegativeInt doesn't have a coercion
112 # helper, since it didn't define any coercions.
113 $value = to_PositiveInt($value) or die "Cannot coerce";
120 The type system provided by Moose effectively makes all of its builtin type
121 global, as are any types you declare with Moose. This means that every module
122 that declares a type named "PositiveInt" is sharing the same type object. This
123 can be a problem when different parts of the code base want to use the same
124 name for different things.
126 This package lets you declare types using short names, but behind the scenes
127 it namespaces all your type declarations, effectively prevent name clashes
130 This is done by creating a type library module like C<MyApp::Types> and then
131 importing types from that module into other modules.
133 As a side effect, the declaration mechanism allows you to write type names as
134 barewords (really function calls), which catches typos in names at compile
135 time rather than run time.
137 This module also provides some helper functions for using Moose types outside
138 of attribute declarations.
140 If you mix string-based names with types created by this module, it will warn,
141 with a few exceptions. If you are declaring a C<class_type()> or
142 C<role_type()> within your type library, or if you use a fully qualified name
143 like C<"MyApp::Foo">.
145 =head1 LIBRARY DEFINITION
147 A MooseX::Types is just a normal Perl module. Unlike Moose
148 itself, it does not install C<use strict> and C<use warnings> in your
149 class by default, so this is up to you.
151 The only thing a library is required to do is
153 use MooseX::Types -declare => \@types;
155 with C<@types> being a list of types you wish to define in this library.
156 This line will install a proper base class in your package as well as the
157 full set of L<handlers|/"TYPE HANDLER FUNCTIONS"> for your declared
158 types. It will then hand control over to L<Moose::Util::TypeConstraints>'
159 C<import> method to export the functions you will need to declare your
162 If you want to use Moose' built-in types (e.g. for subtyping) you will
165 use MooseX::Types::Moose @types;
167 to import the helpers from the shipped L<MooseX::Types::Moose>
168 library which can export all types that come with Moose.
170 You will have to define coercions for your types or your library won't
171 export a L</to_$type> coercion helper for it.
173 Note that you currently cannot define types containing C<::>, since
174 exporting would be a problem.
176 You also don't need to use C<warnings> and C<strict>, since the
177 definition of a library automatically exports those.
181 You can import the L<"type helpers"|/"TYPE HANDLER FUNCTIONS"> of a
182 library by C<use>ing it with a list of types to import as arguments. If
183 you want all of them, use the C<:all> tag. For example:
185 use MyLibrary ':all';
186 use MyOtherLibrary qw( TypeA TypeB );
188 MooseX::Types comes with a library of Moose' built-in types called
189 L<MooseX::Types::Moose>.
191 The exporting mechanism is, since version 0.5, implemented via a wrapper
192 around L<Sub::Exporter>. This means you can do something like this:
194 use MyLibrary TypeA => { -as => 'MyTypeA' },
195 TypeB => { -as => 'MyTypeB' };
197 =head1 TYPE HANDLER FUNCTIONS
201 A constant with the name of your type. It contains the type's fully
202 qualified name. Takes no value, as all constants.
206 This handler takes a value and tests if it is a valid value for this
207 C<$type>. It will return true or false.
211 A handler that will take a value and coerce it into the C<$type>. It will
212 return a false value if the type could not be coerced.
214 B<Important Note>: This handler will only be exported for types that can
215 do type coercion. This has the advantage that a coercion to a type that
216 has not defined any coercions will lead to a compile-time error.
218 =head1 WRAPPING A LIBRARY
220 You can define your own wrapper subclasses to manipulate the behaviour
221 of a set of library exports. Here is an example:
226 use base 'MooseX::Types::Wrapper';
228 sub coercion_export_generator {
230 my $code = $class->next::method(@_);
232 my $value = $code->(@_);
233 warn "Coercion returned undef!"
234 unless defined $value;
241 This class wraps the coercion generator (e.g., C<to_Int()>) and warns
242 if a coercion returned an undefined value. You can wrap any library
247 use MyWrapper MyLibrary => [qw( Foo Bar )],
248 Moose => [qw( Str Int )];
253 The C<Moose> library name is a special shortcut for L<MooseX::Types::Moose>.
255 =head2 Generator methods you can overload
259 =item type_export_generator( $short, $full )
261 Creates a closure returning the type's L<Moose::Meta::TypeConstraint> object.
263 =item check_export_generator( $short, $full, $undef_message )
265 This creates the closure used to test if a value is valid for this type.
267 =item coercion_export_generator( $short, $full, $undef_message )
269 This is the closure that's doing coercions.
273 =head2 Provided Parameters
279 The short, exported name of the type.
283 The fully qualified name of this type as L<Moose> knows it.
287 A message that will be thrown when type functionality is used but the
288 type does not yet exist.
292 =head1 RECURSIVE SUBTYPES
294 As of version 0.08, L<Moose::Types> has experimental support for Recursive
295 subtypes. This will allow:
297 subtype Tree() => as HashRef[Str|Tree];
299 Which validates things like:
302 {key=>{subkey1=>'value', subkey2=>'value'}}
304 And so on. This feature is new and there may be lurking bugs so don't be afraid
305 to hunt me down with patches and test cases if you have trouble.
307 =head1 NOTES REGARDING TYPE UNIONS
309 L<MooseX::Types> uses L<MooseX::Types::TypeDecorator> to do some overloading
310 which generally allows you to easily create union types:
312 subtype StrOrArrayRef,
315 As with parameterized constrains, this overloading extends to modules using the
316 types you define in a type library.
319 use MooseX::Types::Moose qw(HashRef Int);
321 has 'attr' => ( isa => HashRef | Int );
323 And everything should just work as you'd think.
329 Installs the L<MooseX::Types::Base> class into the caller and exports types
330 according to the specification described in L</"LIBRARY DEFINITION">. This
331 will continue to L<Moose::Util::TypeConstraints>' C<import> method to export
332 helper functions you will need to declare your types.
337 my ($class, %args) = @_;
340 # everyone should want this
344 # inject base class into new library
346 unshift @{ $caller . '::ISA' }, 'MooseX::Types::Base';
349 # generate predeclared type helpers
350 if (my @orig_declare = @{ $args{ -declare } || [] }) {
351 my ($tags, $declare) = filter_tags @orig_declare;
354 for my $type (@$declare) {
356 croak "Cannot create a type containing '::' ($type) at the moment"
359 # add type to library and remember to export
360 $caller->add_type($type);
361 push @to_export, $type;
364 $caller->import({ -full => 1, -into => $caller }, @to_export);
367 # run type constraints import
368 Moose::Util::TypeConstraints->import({ into => $caller });
370 # override some with versions that check for syntax errors
371 MooseX::Types::CheckedUtilExports->import({ into => $caller });
376 =head2 type_export_generator
378 Generate a type export, e.g. C<Int()>. This will return either a
379 L<Moose::Meta::TypeConstraint> object, or alternatively a
380 L<MooseX::Types::UndefinedType> object if the type was not yet defined.
384 sub type_export_generator {
385 my ($class, $type, $name) = @_;
387 ## Return an anonymous subroutine that will generate the proxied type
388 ## constraint for you.
390 return subname "__TYPE__::$name" => sub {
391 my $type_constraint = $class->create_base_type_constraint($name);
393 if(defined(my $params = shift @_)) {
394 ## We currently only allow a TC to accept a single, ArrayRef
395 ## parameter, as in HashRef[Int], where [Int] is what's inside the
397 if(reftype $params eq 'ARRAY') {
398 $type_constraint = $class->create_arged_type_constraint($name, @$params);
399 } elsif(!defined $type_constraint) {
400 croak "Syntax error in type definition (did you forget a comma"
403 croak "Argument must be an ArrayRef to create a parameterized "
404 . "type, Eg.: ${type}[Int]. Got: ".ref($params)."."
408 $type_constraint = defined($type_constraint) ? $type_constraint
409 : MooseX::Types::UndefinedType->new($name);
411 my $type_decorator = $class->create_type_decorator($type_constraint);
413 ## If there are additional args, that means it's probably stuff that
414 ## needs to be returned to the subtype. Not an ideal solution here but
415 ## doesn't seem to cause trouble.
418 return ($type_decorator, @_);
420 return $type_decorator;
425 =head2 create_arged_type_constraint ($name, @args)
427 Given a String $name with @args find the matching typeconstraint and parameterize
432 sub create_arged_type_constraint {
433 my ($class, $name, @args) = @_;
434 my $type_constraint = Moose::Util::TypeConstraints::find_or_create_type_constraint("$name");
435 my $parameterized = $type_constraint->parameterize(@args);
436 # It's obnoxious to have to parameterize before looking for the TC, but the
437 # alternative is to hard-code the assumption that the name is
438 # "$name[$args[0]]", which would be worse.
439 # This breaks MXMS, unfortunately, which relies on things like Tuple[...]
440 # creating new type objects each time.
442 # Moose::Util::TypeConstraints::find_type_constraint($parameterized->name)) {
445 # Moose::Util::TypeConstraints::register_type_constraint($parameterized);
446 return $parameterized;
449 =head2 create_base_type_constraint ($name)
451 Given a String $name, find the matching type constraint.
455 sub create_base_type_constraint {
456 my ($class, $name) = @_;
457 return find_type_constraint($name);
460 =head2 create_type_decorator ($type_constraint)
462 Given a $type_constraint, return a lightweight L<MooseX::Types::TypeDecorator>
467 sub create_type_decorator {
468 my ($class, $type_constraint) = @_;
469 return MooseX::Types::TypeDecorator->new($type_constraint);
472 =head2 coercion_export_generator
474 This generates a coercion handler function, e.g. C<to_Int($value)>.
478 sub coercion_export_generator {
479 my ($class, $type, $full, $undef_msg) = @_;
483 # we need a type object
484 my $tobj = find_type_constraint($full) or croak $undef_msg;
485 my $return = $tobj->coerce($value);
487 # non-successful coercion returns false
488 return unless $tobj->check($return);
494 =head2 check_export_generator
496 Generates a constraint check closure, e.g. C<is_Int($value)>.
500 sub check_export_generator {
501 my ($class, $type, $full, $undef_msg) = @_;
505 # we need a type object
506 my $tobj = find_type_constraint($full) or croak $undef_msg;
508 return $tobj->check($value);
514 The following are lists of gotchas and their workarounds for developers coming
515 from the standard string based type constraint names
519 A library makes the types quasi-unique by prefixing their names with (by
520 default) the library package name. If you're only using the type handler
521 functions provided by MooseX::Types, you shouldn't ever have to use
522 a type's actual full name.
524 =head2 Argument separation ('=>' versus ',')
526 The L<perlop> manpage has this to say about the '=>' operator: "The => operator is
527 a synonym for the comma, but forces any word (consisting entirely of word
528 characters) to its left to be interpreted as a string (as of 5.001). This
529 includes words that might otherwise be considered a constant or function call."
531 Due to this stringification, the following will NOT work as you might think:
533 subtype StrOrArrayRef => as Str | ArrayRef;
535 The 'StrOrArrayRef' will have its stringification activated this causes the
536 subtype to not be created. Since the bareword type constraints are not strings
537 you really should not try to treat them that way. You will have to use the ','
538 operator instead. The author's of this package realize that all the L<Moose>
539 documention and examples nearly uniformly use the '=>' version of the comma
540 operator and this could be an issue if you are converting code.
542 Patches welcome for discussion.
544 =head2 Compatibility with Sub::Exporter
546 If you want to use L<Sub::Exporter> with a Type Library, you need to make sure
547 you export all the type constraints declared AS WELL AS any additional export
548 targets. For example if you do:
550 package TypeAndSubExporter;
552 use MooseX::Types::Moose qw(Str);
553 use MooseX::Types -declare => [qw(MyStr)];
554 use Sub::Exporter -setup => { exports => [qw(something)] };
556 subtype MyStr, as Str;
562 # then in another module ...
565 use TypeAndSubExporter qw(MyStr);
567 You'll get a '"MyStr" is not exported by the TypeAndSubExporter module' error.
568 Upi can workaround by:
570 - use Sub::Exporter -setup => { exports => [ qw(something) ] };
571 + use Sub::Exporter -setup => { exports => [ qw(something MyStr) ] };
573 This is a workaround and I am exploring how to make these modules work better
574 together. I realize this workaround will lead a lot of duplication in your
575 export declarations and will be onerous for large type libraries. Patches and
576 detailed test cases welcome. See the tests directory for a start on this.
578 =head1 COMBINING TYPE LIBRARIES
580 You may want to combine a set of types for your application with other type
581 libraries, like L<MooseX::Types::Moose> or L<MooseX::Types::Common::String>.
583 The L<MooseX::Types::Combine> module provides a simple API for combining a set
584 of type libraries together.
588 L<Moose>, L<Moose::Util::TypeConstraints>, L<MooseX::Types::Moose>,
591 =head1 ACKNOWLEDGEMENTS
593 Many thanks to the C<#moose> cabal on C<irc.perl.org>.
597 jnapiorkowski: John Napiorkowski <jjnapiork@cpan.org>
599 caelum: Rafael Kitover <rkitover@cpan.org>
601 rafl: Florian Ragwitz <rafl@debian.org>
603 hdp: Hans Dieter Pearcey <hdp@cpan.org>
605 autarch: Dave Rolsky <autarch@urth.org>