6 Moose::Cookbook::Basics::Recipe5 - More subtypes, coercion in a B<Request> class
12 use Moose::Util::TypeConstraints;
15 use Params::Coerce ();
18 class_type('HTTP::Headers');
20 coerce 'HTTP::Headers'
22 => via { HTTP::Headers->new( @{$_} ) }
24 => via { HTTP::Headers->new( %{$_} ) };
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 => 'URI', coerce => 1 );
41 has 'uri' => ( is => 'rw', isa => 'URI', coerce => 1 );
42 has 'method' => ( is => 'rw', isa => 'Str' );
43 has 'protocol' => ( is => 'rw', isa => 'Protocol' );
46 isa => '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 parameter to a true value.
62 First, we create the subtype to which we will coerce the other types:
64 class_type('HTTP::Headers');
66 The C<class_type> sugar function is simply a shortcut for something
69 subtype 'HTTP::Headers'
71 => where { $_->isa('HTTP::Headers') };
73 Internally, Moose creates a type constraint for each Moose-using
74 class, but for non-Moose classes, the type must be declared
77 We could go ahead and use this new type directly:
81 isa => 'HTTP::Headers',
82 default => sub { HTTP::Headers->new }
85 This creates a simple attribute which defaults to an empty instance of
88 The constructor for L<HTTP::Headers> accepts a list of key-value pairs
89 representing the HTTP header fields. In Perl, such a list could be
90 stored in an ARRAY or HASH reference. We want our C<headers> attribute
91 to accept those data structure instead of an B<HTTP::Headers>
92 instance, and just do the right thing. This is exactly what coercion
95 coerce 'HTTP::Headers'
97 => via { HTTP::Headers->new( @{$_} ) }
99 => via { HTTP::Headers->new( %{$_} ) };
101 The first argument to c<coerce> is the type I<to> which we are
102 coercing. Then we give it a set of C<from>/C<via> clauses. The C<from>
103 function takes some other type name and C<via> takes a subroutine
104 reference which actually does the coercion.
106 However, defining the coercion doesn't do anything until we tell Moose
107 we want a particular attribute to be coerced:
113 default => sub { HTTP::Headers->new }
116 Now, if we use an C<ArrayRef> or C<HashRef> to populate C<headers>, it
117 will be coerced into a new L<HTTP::Headers> instance. With the
118 coercion in place, the following lines of code are all equivalent:
120 $foo->headers( HTTP::Headers->new( bar => 1, baz => 2 ) );
121 $foo->headers( [ 'bar', 1, 'baz', 2 ] );
122 $foo->headers( { bar => 1, baz => 2 } );
124 As you can see, careful use of coercions can produce a very open
125 interface for your class, while still retaining the "safety" of your
126 type constraint checks. (1)
128 Our next coercion shows how we can leverage existing CPAN modules to
129 help implement coercions. In this case we use L<Params::Coerce>.
131 Once again, we need to declare a class type for our non-Moose L<URI>
136 Then we define the coercion:
140 => via { $_->isa('URI')
142 : Params::Coerce::coerce( 'URI', $_ ); }
144 => via { URI->new( $_, 'http' ) };
146 The first coercion takes any object and makes it a C<URI> object. The
147 coercion system isn't that smart, and does not check if the object is
148 already a L<URI>, so we check for that ourselves. If it's not a L<URI>
149 already, we let L<Params::Coerce> do its magic, and we just use its
152 If L<Params::Coerce> didn't return a L<URI> object (for whatever
153 reason), Moose would throw a type constraint error.
155 The other coercion takes a string and converts to a L<URI>. In this
156 case, we are using the coercion to apply a default behavior, where a
157 string is assumed to be an C<http> URI.
159 Finally, we need to make sure our attributes enable coercion.
161 has 'base' => ( is => 'rw', isa => 'URI', coerce => 1 );
162 has 'uri' => ( is => 'rw', isa => 'URI', coerce => 1 );
164 Re-using the coercion lets us enforce a consistent API across multiple
169 This recipe showed the use of coercions to create a more flexible and
170 DWIM-y API. Like any powerful magic, we recommend some
171 caution. Sometimes it's better to reject a value than just guess at
174 We also showed the use of the C<class_type> sugar function as a
175 shortcut for defining a new subtype of C<Object>
183 This particular example could be safer. Really we only want to coerce
184 an array with an I<even> number of elements. We could create a new
185 C<EvenElementArrayRef> type, and then coerce from that type, as
186 opposed to from a plain C<ArrayRef>
192 Stevan Little E<lt>stevan@iinteractive.comE<gt>
194 Dave Rolsky E<lt>autarch@urth.orgE<gt>
196 =head1 COPYRIGHT AND LICENSE
198 Copyright 2006-2009 by Infinity Interactive, Inc.
200 L<http://www.iinteractive.com>
202 This library is free software; you can redistribute it and/or modify
203 it under the same terms as Perl itself.