fix manual typo
[gitmo/Moose.git] / lib / Moose / Manual / Roles.pod
CommitLineData
daa0fd7d 1package Moose::Manual::Roles;
2
3# ABSTRACT: Roles, an alternative to deep hierarchies and base classes
ef45e915 4
daa0fd7d 5__END__
ef45e915 6
daa0fd7d 7=pod
ef45e915 8
9=head1 WHAT IS A ROLE?
10
909103e1 11A role encapsulates some piece of behavior or state that can be shared between
7d628d04 12classes. It is something that classes I<do>. It is important to understand that
909103e1 13I<roles are not classes>. You cannot inherit from a role, and a role cannot be
14instantiated. We sometimes say that roles are I<consumed>, either by classes
15or other roles.
ef45e915 16
17Instead, a role is I<composed> into a class. In practical terms, this
909103e1 18means that all of the methods, method modifiers, and attributes defined in a role are
ca426a3a 19added directly to (we sometimes say "flattened into") the class that
20consumes the role. These attributes and methods then appear as if they
c89a5d69 21were defined in the class itself. A subclass of the consuming class
22will inherit all of these methods and attributes.
ef45e915 23
24Moose roles are similar to mixins or interfaces in other languages.
25
26Besides defining their own methods and attributes, roles can also
27require that the consuming class define certain methods of its
28own. You could have a role that consisted only of a list of required
29methods, in which case the role would be very much like a Java
30interface.
31
92fcea04 32Note that attribute accessors also count as methods for the
909103e1 33purposes of satisfying the requirements of a role.
92fcea04 34
ef45e915 35=head1 A SIMPLE ROLE
36
37Creating a role looks a lot like creating a Moose class:
38
39 package Breakable;
40
41 use Moose::Role;
42
43 has 'is_broken' => (
44 is => 'rw',
45 isa => 'Bool',
46 );
47
48 sub break {
49 my $self = shift;
50
51 print "I broke\n";
52
53 $self->is_broken(1);
54 }
55
0c39debe 56Except for our use of L<Moose::Role>, this looks just like a class
ef45e915 57definition with Moose. However, this is not a class, and it cannot be
58instantiated.
59
60Instead, its attributes and methods will be composed into classes
61which use the role:
62
63 package Car;
64
65 use Moose;
66
67 with 'Breakable';
68
69 has 'engine' => (
70 is => 'ro',
71 isa => 'Engine',
72 );
73
74The C<with> function composes roles into a class. Once that is done,
75the C<Car> class has an C<is_broken> attribute and a C<break>
76method. The C<Car> class also C<does('Breakable')>:
77
c56e5db4 78 my $car = Car->new( engine => Engine->new );
ef45e915 79
d29608ef 80 print $car->is_broken ? 'Busted' : 'Still working';
c56e5db4 81 $car->break;
d29608ef 82 print $car->is_broken ? 'Busted' : 'Still working';
ef45e915 83
84 $car->does('Breakable'); # true
85
86This prints:
87
88 Still working
89 I broke
90 Busted
91
92We could use this same role in a C<Bone> class:
93
94 package Bone;
95
96 use Moose;
97
98 with 'Breakable';
99
100 has 'marrow' => (
101 is => 'ro',
102 isa => 'Marrow',
103 );
104
9956dcf4 105See also L<Moose::Cookbook::Roles::Comparable_CodeReuse> for an example.
b9cb323b 106
ef45e915 107=head1 REQUIRED METHODS
108
109As mentioned previously, a role can require that consuming classes
110provide one or more methods. Using our C<Breakable> example, let's
111make it require that consuming classes implement their own C<break>
112methods:
113
114 package Breakable;
115
116 use Moose::Role;
117
118 requires 'break';
119
120 has 'is_broken' => (
121 is => 'rw',
122 isa => 'Bool',
123 );
124
125 after 'break' => sub {
126 my $self = shift;
127
128 $self->is_broken(1);
c56e5db4 129 };
ef45e915 130
131If we try to consume this role in a class that does not have a
132C<break> method, we will get an exception.
133
ca426a3a 134You can see that we added a method modifier on C<break>. We want
135classes that consume this role to implement their own logic for
136breaking, but we make sure that the C<is_broken> attribute is always
137set to true when C<break> is called.
ef45e915 138
139 package Car
140
ca426a3a 141 use Moose;
ef45e915 142
143 with 'Breakable';
144
145 has 'engine' => (
146 is => 'ro',
147 isa => 'Engine',
148 );
149
150 sub break {
151 my $self = shift;
152
c56e5db4 153 if ( $self->is_moving ) {
154 $self->stop;
ef45e915 155 }
156 }
157
c89a5d69 158=head2 Roles Versus Abstract Base Classes
159
160If you are familiar with the concept of abstract base classes in other
161languages, you may be tempted to use roles in the same way.
162
398e8913 163You I<can> define an "interface-only" role, one that contains I<just>
164a list of required methods.
c89a5d69 165
166However, any class which consumes this role must implement all of the
167required methods, either directly or through inheritance from a
168parent. You cannot delay the method requirement check so that they can
169be implemented by future subclasses.
170
171Because the role defines the required methods directly, adding a base
172class to the mix would not achieve anything. We recommend that you
173simply consume the interface role in each class which implements that
174interface.
175
4ec0c7fe 176=head2 Required Attributes
177
909103e1 178As mentioned before, a role's required method may also be satisfied by an
179attribute accessor. However, the call to C<has> which defines an attribute
180happens at runtime. This means that you must define the attribute I<before>
181consuming the role, or else the role will not see the generated accessor.
4ec0c7fe 182
183 package Breakable;
184
185 use Moose::Role;
186
187 requires 'stress';
188
189 package Car;
190
191 use Moose;
192
909103e1 193 has 'stress' => (
4ec0c7fe 194 is => 'rw',
bea7e77e 195 isa => 'Int',
4ec0c7fe 196 );
197
198 with 'Breakable';
199
ef45e915 200=head1 USING METHOD MODIFIERS
201
202Method modifiers and roles are a very powerful combination. Often, a
203role will combine method modifiers and required methods. We already
204saw one example with our C<Breakable> example.
205
eb169874 206Method modifiers increase the complexity of roles, because they make
c56e5db4 207the role application order relevant. If a class uses multiple roles,
208each of which modify the same method, those modifiers will be applied
209in the same order as the roles are used:
eb169874 210
211 package MovieCar;
212
213 use Moose;
214
215 extends 'Car';
216
217 with 'Breakable', 'ExplodesOnBreakage';
218
ad337e36 219Assuming that the new C<ExplodesOnBreakage> role I<also> has an
eb169874 220C<after> modifier on C<break>, the C<after> modifiers will run one
221after the other. The modifier from C<Breakable> will run first, then
222the one from C<ExplodesOnBreakage>.
223
224=head1 METHOD CONFLICTS
225
226If a class composes multiple roles, and those roles have methods of
227the same name, we will have a conflict. In that case, the composing
228class is required to provide its I<own> method of the same name.
229
dab94063 230 package Breakdancer;
eb169874 231
232 use Moose::Role
233
234 sub break {
235
236 }
237
238If we compose both C<Breakable> and C<Breakdancer> in a class, we must
239provide our own C<break> method:
240
241 package FragileDancer;
242
243 use Moose;
244
245 with 'Breakable', 'Breakdancer';
ef45e915 246
c56e5db4 247 sub break { ... }
248
b9cb323b 249A role can be a collection of other roles:
250
251 package Break::Bundle;
252
253 use Moose::Role;
254
255 with ('Breakable', 'Breakdancer');
256
c56e5db4 257=head1 METHOD EXCLUSION AND ALIASING
258
259If we want our C<FragileDancer> class to be able to call the methods
260from both its roles, we can alias the methods:
261
262 package FragileDancer;
263
264 use Moose;
265
c8b8d92f 266 with 'Breakable' => { -alias => { break => 'break_bone' } },
267 'Breakdancer' => { -alias => { break => 'break_dance' } };
c56e5db4 268
269However, aliasing a method simply makes a I<copy> of the method with
270the new name. We also need to exclude the original name:
271
272 with 'Breakable' => {
c8b8d92f 273 -alias => { break => 'break_bone' },
274 -excludes => 'break',
c56e5db4 275 },
276 'Breakdancer' => {
c8b8d92f 277 -alias => { break => 'break_dance' },
278 -excludes => 'break',
c56e5db4 279 };
280
ffb800c0 281The excludes parameter prevents the C<break> method from being composed
c56e5db4 282into the C<FragileDancer> class, so we don't have a conflict. This
283means that C<FragileDancer> does not need to implement its own
284C<break> method.
285
286This is useful, but it's worth noting that this breaks the contract
287implicit in consuming a role. Our C<FragileDancer> class does both the
288C<Breakable> and C<BreakDancer>, but does not provide a C<break>
289method. If some API expects an object that does one of those roles, it
290probably expects it to implement that method.
291
ca426a3a 292In some use cases we might alias and exclude methods from roles, but
293then provide a method of the same name in the class itself.
294
706d2d37 295Also see L<Moose::Cookbook::Roles::Restartable_AdvancedComposition> for an example.
b9cb323b 296
ca426a3a 297=head1 ROLE EXCLUSION
298
299A role can say that it cannot be combined with some other role. This
300should be used with great caution, since it limits the re-usability of
301the role.
302
303 package Breakable;
304
305 use Moose::Role;
306
307 excludes 'BreakDancer';
308
40edf959 309=head1 ADDING A ROLE TO AN OBJECT INSTANCE
310
909103e1 311You may want to add a role to an object instance, rather than to a class. For
312example, you may want to add debug tracing to one instance of an object while
313debugging a particular bug. Another use case might be to dynamically change
314objects based on a user's configuration, as a plugin system.
40edf959 315
909103e1 316The best way to do this is to use the C<apply_all_roles()> function from
40edf959 317L<Moose::Util>:
318
319 use Moose::Util qw( apply_all_roles );
320
321 my $car = Car->new;
322 apply_all_roles( $car, 'Breakable' );
323
324This function can apply more than one role at a time, and will do so using the
325normal Moose role combination system. We recommend using this function to
326apply roles to an object. This is what Moose uses internally when you call
327C<with>.
328
a4bd85ad 329=cut