Be consistent and say "attribute option(s)", not "parameter(s)"
[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   subtype 'My.HTTP::Headers' => as class_type('HTTP::Headers');
19
20   coerce 'My.HTTP::Headers'
21       => from 'ArrayRef'
22           => via { HTTP::Headers->new( @{$_} ) }
23       => from 'HashRef'
24           => via { HTTP::Headers->new( %{$_} ) };
25
26   subtype 'My.URI' => as class_type('HTTP::Headers');
27
28   coerce 'My.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 => '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' );
44   has 'headers'  => (
45       is      => 'rw',
46       isa     => 'My.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 option to a true value.
61
62 First, we create the subtype to which we will coerce the other types:
63
64   subtype 'My.HTTP::Headers' => as class_type('HTTP::Headers');
65
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.
72
73 The C<class_type> sugar function is simply a shortcut for this:
74
75   subtype 'HTTP::Headers'
76       => as 'Object'
77       => where { $_->isa('HTTP::Headers') };
78
79 Internally, Moose creates a type constraint for each Moose-using
80 class, but for non-Moose classes, the type must be declared
81 explicitly.
82
83 We could go ahead and use this new type directly:
84
85   has 'headers' => (
86       is      => 'rw',
87       isa     => 'HTTP::Headers',
88       default => sub { HTTP::Headers->new }
89   );
90
91 This creates a simple attribute which defaults to an empty instance of
92 L<HTTP::Headers>.
93
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
99 is for:
100
101   coerce 'My.HTTP::Headers'
102       => from 'ArrayRef'
103           => via { HTTP::Headers->new( @{$_} ) }
104       => from 'HashRef'
105           => via { HTTP::Headers->new( %{$_} ) };
106
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.
111
112 However, defining the coercion doesn't do anything until we tell Moose
113 we want a particular attribute to be coerced:
114
115   has 'headers' => (
116       is      => 'rw',
117       isa     => 'My.HTTP::Headers',
118       coerce  => 1,
119       default => sub { HTTP::Headers->new }
120   );
121
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:
125
126   $foo->headers( HTTP::Headers->new( bar => 1, baz => 2 ) );
127   $foo->headers( [ 'bar', 1, 'baz', 2 ] );
128   $foo->headers( { bar => 1, baz => 2 } );
129
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)
133
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>.
136
137 Once again, we need to declare a class type for our non-Moose L<URI>
138 class:
139
140   subtype 'My.URI' => as class_type('HTTP::Headers');
141
142 Then we define the coercion:
143
144   coerce 'My.URI'
145       => from 'Object'
146           => via { $_->isa('URI')
147                    ? $_
148                    : Params::Coerce::coerce( 'URI', $_ ); }
149       => from 'Str'
150           => via { URI->new( $_, 'http' ) };
151
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
156 return value.
157
158 If L<Params::Coerce> didn't return a L<URI> object (for whatever
159 reason), Moose would throw a type constraint error.
160
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.
164
165 Finally, we need to make sure our attributes enable coercion.
166
167   has 'base' => ( is => 'rw', isa => 'My.URI', coerce => 1 );
168   has 'uri'  => ( is => 'rw', isa => 'My.URI', coerce => 1 );
169
170 Re-using the coercion lets us enforce a consistent API across multiple
171 attributes.
172
173 =head1 CONCLUSION
174
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
178 how to DWIM.
179
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>
182
183 =head1 FOOTNOTES
184
185 =over 4
186
187 =item (1)
188
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>
193
194 =back
195
196 =head1 AUTHORS
197
198 Stevan Little E<lt>stevan@iinteractive.comE<gt>
199
200 Dave Rolsky E<lt>autarch@urth.orgE<gt>
201
202 =head1 COPYRIGHT AND LICENSE
203
204 Copyright 2006-2009 by Infinity Interactive, Inc.
205
206 L<http://www.iinteractive.com>
207
208 This library is free software; you can redistribute it and/or modify
209 it under the same terms as Perl itself.
210
211 =cut