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