Made an editorial pass through basics recipe 5
[gitmo/Moose.git] / lib / Moose / Cookbook / Basics / Recipe5.pod
1
2 =pod
3
4 =head1 NAME
5
6 Moose::Cookbook::Basics::Recipe5 - More subtypes, coercion in a B<Request> class
7
8 =head1 SYNOPSIS
9
10   package Request;
11   use Moose;
12   use Moose::Util::TypeConstraints;
13
14   use HTTP::Headers  ();
15   use Params::Coerce ();
16   use URI            ();
17
18   class_type('HTTP::Headers');
19
20   coerce 'HTTP::Headers'
21       => from 'ArrayRef'
22           => via { HTTP::Headers->new( @{$_} ) }
23       => from 'HashRef'
24           => via { HTTP::Headers->new( %{$_} ) };
25
26   class_type('URI');
27
28   coerce 'URI'
29       => from 'Object'
30           => via { $_->isa('URI')
31                    ? $_
32                    : Params::Coerce::coerce( 'URI', $_ ); }
33       => from 'Str'
34           => via { URI->new( $_, 'http' ) };
35
36   subtype 'Protocol'
37       => as 'Str'
38       => where { /^HTTP\/[0-9]\.[0-9]$/ };
39
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' );
44   has 'headers'  => (
45       is      => 'rw',
46       isa     => 'HTTP::Headers',
47       coerce  => 1,
48       default => sub { HTTP::Headers->new }
49   );
50
51 =head1 DESCRIPTION
52
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
56 another.
57
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.
61
62 First, we create the subtype to which we will coerce the other types:
63
64   class_type('HTTP::Headers');
65
66 The C<class_type> sugar function is simply a shortcut for something
67 like this:
68
69   subtype 'HTTP::Headers'
70       => as 'Object'
71       => where { $_->isa('HTTP::Headers') };
72
73 Internally, Moose creates a type constraint for each Moose-using
74 class, but for non-Moose classes, the type must be declared
75 explicitly.
76
77 We could go ahead and use this new type directly:
78
79   has 'headers' => (
80       is      => 'rw',
81       isa     => 'HTTP::Headers',
82       default => sub { HTTP::Headers->new }
83   );
84
85 This creates a simple attribute which defaults to an empty instance of
86 L<HTTP::Headers>.
87
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
93 is for:
94
95   coerce 'HTTP::Headers'
96       => from 'ArrayRef'
97           => via { HTTP::Headers->new( @{$_} ) }
98       => from 'HashRef'
99           => via { HTTP::Headers->new( %{$_} ) };
100
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.
105
106 However, defining the coercion doesn't do anything until we tell Moose
107 we want a particular attribute to be coerced:
108
109   has 'headers' => (
110       is      => 'rw',
111       isa     => 'Header',
112       coerce  => 1,
113       default => sub { HTTP::Headers->new }
114   );
115
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:
119
120   $foo->headers( HTTP::Headers->new( bar => 1, baz => 2 ) );
121   $foo->headers( [ 'bar', 1, 'baz', 2 ] );
122   $foo->headers( { bar => 1, baz => 2 } );
123
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)
127
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>.
130
131 Once again, we need to declare a class type for our non-Moose L<URI>
132 class:
133
134   class_type('URI');
135
136 Then we define the coercion:
137
138   coerce 'URI'
139       => from 'Object'
140           => via { $_->isa('URI')
141                    ? $_
142                    : Params::Coerce::coerce( 'URI', $_ ); }
143       => from 'Str'
144           => via { URI->new( $_, 'http' ) };
145
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
150 return value.
151
152 If L<Params::Coerce> didn't return a L<URI> object (for whatever
153 reason), Moose would throw a type constraint error.
154
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.
158
159 Finally, we need to make sure our attributes enable coercion.
160
161   has 'base' => ( is => 'rw', isa => 'URI', coerce => 1 );
162   has 'uri'  => ( is => 'rw', isa => 'URI', coerce => 1 );
163
164 Re-using the coercion lets us enforce a consistent API across multiple
165 attributes.
166
167 =head1 CONCLUSION
168
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
172 how to DWIM.
173
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>
176
177 =head1 FOOTNOTES
178
179 =over 4
180
181 =item (1)
182
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>
187
188 =back
189
190 =head1 AUTHORS
191
192 Stevan Little E<lt>stevan@iinteractive.comE<gt>
193
194 Dave Rolsky E<lt>autarch@urth.orgE<gt>
195
196 =head1 COPYRIGHT AND LICENSE
197
198 Copyright 2006-2009 by Infinity Interactive, Inc.
199
200 L<http://www.iinteractive.com>
201
202 This library is free software; you can redistribute it and/or modify
203 it under the same terms as Perl itself.
204
205 =cut