6 Moose::Cookbook::Basics::Recipe5 - More subtypes, coercion in a B<Request> class
12 use Moose::Util::TypeConstraints;
15 use Params::Coerce ();
18 subtype 'My.HTTP::Headers' => as class_type('HTTP::Headers');
20 coerce 'My.HTTP::Headers'
22 => via { HTTP::Headers->new( @{$_} ) }
24 => via { HTTP::Headers->new( %{$_} ) };
26 subtype 'My.URI' => as class_type('HTTP::Headers');
30 => via { $_->isa('URI')
32 : Params::Coerce::coerce( 'URI', $_ ); }
34 => via { URI->new( $_, 'http' ) };
38 => where { /^HTTP\/[0-9]\.[0-9]$/ };
40 has 'base' => ( is => 'rw', isa => 'My.URI', coerce => 1 );
41 has 'uri' => ( is => 'rw', isa => 'My.URI', coerce => 1 );
42 has 'method' => ( is => 'rw', isa => 'Str' );
43 has 'protocol' => ( is => 'rw', isa => 'Protocol' );
46 isa => 'My.HTTP::Headers',
48 default => sub { HTTP::Headers->new }
53 This recipe introduces type coercions, which are defined with the
54 C<coerce> sugar function. Coercions are attached to existing type
55 constraints, and define a (one-way) transformation from one type to
58 This is very powerful, but it's also magical, so you have to
59 explicitly ask for an attribute to be coerced. To do this, you must
60 set the C<coerce> attribute option to a true value.
62 First, we create the subtype to which we will coerce the other types:
64 subtype 'My.HTTP::Headers' => as class_type('HTTP::Headers');
66 We are creating a subtype rather than using C<HTTP::Headers> as a type
67 directly. The reason we do this is coercions are global, and a
68 coercion defined for C<HTTP::Headers> in our C<Request> class would
69 then be defined for I<all> Moose-using classes in the current Perl
70 interpreter. It's a L<best practice|Moose::Manual::BestPractices> to
71 avoid this sort of namespace pollution.
73 The C<class_type> sugar function is simply a shortcut for this:
75 subtype 'HTTP::Headers'
77 => where { $_->isa('HTTP::Headers') };
79 Internally, Moose creates a type constraint for each Moose-using
80 class, but for non-Moose classes, the type must be declared
83 We could go ahead and use this new type directly:
87 isa => 'HTTP::Headers',
88 default => sub { HTTP::Headers->new }
91 This creates a simple attribute which defaults to an empty instance of
94 The constructor for L<HTTP::Headers> accepts a list of key-value pairs
95 representing the HTTP header fields. In Perl, such a list could be
96 stored in an ARRAY or HASH reference. We want our C<headers> attribute
97 to accept those data structure instead of an B<HTTP::Headers>
98 instance, and just do the right thing. This is exactly what coercion
101 coerce 'My.HTTP::Headers'
103 => via { HTTP::Headers->new( @{$_} ) }
105 => via { HTTP::Headers->new( %{$_} ) };
107 The first argument to c<coerce> is the type I<to> which we are
108 coercing. Then we give it a set of C<from>/C<via> clauses. The C<from>
109 function takes some other type name and C<via> takes a subroutine
110 reference which actually does the coercion.
112 However, defining the coercion doesn't do anything until we tell Moose
113 we want a particular attribute to be coerced:
117 isa => 'My.HTTP::Headers',
119 default => sub { HTTP::Headers->new }
122 Now, if we use an C<ArrayRef> or C<HashRef> to populate C<headers>, it
123 will be coerced into a new L<HTTP::Headers> instance. With the
124 coercion in place, the following lines of code are all equivalent:
126 $foo->headers( HTTP::Headers->new( bar => 1, baz => 2 ) );
127 $foo->headers( [ 'bar', 1, 'baz', 2 ] );
128 $foo->headers( { bar => 1, baz => 2 } );
130 As you can see, careful use of coercions can produce a very open
131 interface for your class, while still retaining the "safety" of your
132 type constraint checks. (1)
134 Our next coercion shows how we can leverage existing CPAN modules to
135 help implement coercions. In this case we use L<Params::Coerce>.
137 Once again, we need to declare a class type for our non-Moose L<URI>
140 subtype 'My.URI' => as class_type('HTTP::Headers');
142 Then we define the coercion:
146 => via { $_->isa('URI')
148 : Params::Coerce::coerce( 'URI', $_ ); }
150 => via { URI->new( $_, 'http' ) };
152 The first coercion takes any object and makes it a C<URI> object. The
153 coercion system isn't that smart, and does not check if the object is
154 already a L<URI>, so we check for that ourselves. If it's not a L<URI>
155 already, we let L<Params::Coerce> do its magic, and we just use its
158 If L<Params::Coerce> didn't return a L<URI> object (for whatever
159 reason), Moose would throw a type constraint error.
161 The other coercion takes a string and converts to a L<URI>. In this
162 case, we are using the coercion to apply a default behavior, where a
163 string is assumed to be an C<http> URI.
165 Finally, we need to make sure our attributes enable coercion.
167 has 'base' => ( is => 'rw', isa => 'My.URI', coerce => 1 );
168 has 'uri' => ( is => 'rw', isa => 'My.URI', coerce => 1 );
170 Re-using the coercion lets us enforce a consistent API across multiple
175 This recipe showed the use of coercions to create a more flexible and
176 DWIM-y API. Like any powerful magic, we recommend some
177 caution. Sometimes it's better to reject a value than just guess at
180 We also showed the use of the C<class_type> sugar function as a
181 shortcut for defining a new subtype of C<Object>
189 This particular example could be safer. Really we only want to coerce
190 an array with an I<even> number of elements. We could create a new
191 C<EvenElementArrayRef> type, and then coerce from that type, as
192 opposed to from a plain C<ArrayRef>
198 Stevan Little E<lt>stevan@iinteractive.comE<gt>
200 Dave Rolsky E<lt>autarch@urth.orgE<gt>
202 =head1 COPYRIGHT AND LICENSE
204 Copyright 2006-2009 by Infinity Interactive, Inc.
206 L<http://www.iinteractive.com>
208 This library is free software; you can redistribute it and/or modify
209 it under the same terms as Perl itself.