5 Moose::Manual::Roles - Roles, an alternative to deep hierarchies and base classes
9 A role is something that classes do. Usually, a role encapsulates some
10 piece of behavior or state that can be shared between classes. It is
11 important to understand that I<roles are not classes>. You cannot
12 inherit from a role, and a role cannot be instantiated. We sometimes
13 say that roles are I<consumed>, either by classes or other roles.
15 Instead, a role is I<composed> into a class. In practical terms, this
16 means that all of the methods and attributes defined in a role are
17 added directly to (we sometimes say "flattened into") the class that
18 consumes the role. These attributes and methods then appear as if they
19 were defined in the class itself. A subclass of the consuming class
20 will inherit all of these methods and attributes.
22 Moose roles are similar to mixins or interfaces in other languages.
24 Besides defining their own methods and attributes, roles can also
25 require that the consuming class define certain methods of its
26 own. You could have a role that consisted only of a list of required
27 methods, in which case the role would be very much like a Java
30 Note that attribute accessors also count as methods for the
31 purposes of satisfying the requirements of a role.
35 Creating a role looks a lot like creating a Moose class:
54 Except for our use of L<Moose::Role>, this looks just like a class
55 definition with Moose. However, this is not a class, and it cannot be
58 Instead, its attributes and methods will be composed into classes
72 The C<with> function composes roles into a class. Once that is done,
73 the C<Car> class has an C<is_broken> attribute and a C<break>
74 method. The C<Car> class also C<does('Breakable')>:
76 my $car = Car->new( engine => Engine->new );
78 print $car->is_broken ? 'Still working' : 'Busted';
80 print $car->is_broken ? 'Still working' : 'Busted';
82 $car->does('Breakable'); # true
90 We could use this same role in a C<Bone> class:
103 See also L<Moose::Cookbook::Roles::Recipe1> for an example.
105 =head1 REQUIRED METHODS
107 As mentioned previously, a role can require that consuming classes
108 provide one or more methods. Using our C<Breakable> example, let's
109 make it require that consuming classes implement their own C<break>
123 after 'break' => sub {
129 If we try to consume this role in a class that does not have a
130 C<break> method, we will get an exception.
132 You can see that we added a method modifier on C<break>. We want
133 classes that consume this role to implement their own logic for
134 breaking, but we make sure that the C<is_broken> attribute is always
135 set to true when C<break> is called.
151 if ( $self->is_moving ) {
156 =head2 Roles Versus Abstract Base Classes
158 If you are familiar with the concept of abstract base classes in other
159 languages, you may be tempted to use roles in the same way.
161 You I<can> define an "interface-only" role, one that contains I<just>
162 a list of required methods.
164 However, any class which consumes this role must implement all of the
165 required methods, either directly or through inheritance from a
166 parent. You cannot delay the method requirement check so that they can
167 be implemented by future subclasses.
169 Because the role defines the required methods directly, adding a base
170 class to the mix would not achieve anything. We recommend that you
171 simply consume the interface role in each class which implements that
174 =head2 Required Attributes
176 As mentioned before, a role requirement may also be satisfied by an
177 attribute accessor. But any C<has> functions, which will generate
178 accessors that satisfy the role requirement, must be placed
179 I<before> the C<with> function that composes the role.
198 =head1 USING METHOD MODIFIERS
200 Method modifiers and roles are a very powerful combination. Often, a
201 role will combine method modifiers and required methods. We already
202 saw one example with our C<Breakable> example.
204 Method modifiers increase the complexity of roles, because they make
205 the role application order relevant. If a class uses multiple roles,
206 each of which modify the same method, those modifiers will be applied
207 in the same order as the roles are used:
215 with 'Breakable', 'ExplodesOnBreakage';
217 Assuming that the new C<ExplodesOnBreakage> method I<also> has an
218 C<after> modifier on C<break>, the C<after> modifiers will run one
219 after the other. The modifier from C<Breakable> will run first, then
220 the one from C<ExplodesOnBreakage>.
222 =head1 METHOD CONFLICTS
224 If a class composes multiple roles, and those roles have methods of
225 the same name, we will have a conflict. In that case, the composing
226 class is required to provide its I<own> method of the same name.
236 If we compose both C<Breakable> and C<Breakdancer> in a class, we must
237 provide our own C<break> method:
239 package FragileDancer;
243 with 'Breakable', 'Breakdancer';
247 A role can be a collection of other roles:
249 package Break::Bundle;
253 with ('Breakable', 'Breakdancer');
255 =head1 METHOD EXCLUSION AND ALIASING
257 If we want our C<FragileDancer> class to be able to call the methods
258 from both its roles, we can alias the methods:
260 package FragileDancer;
264 with 'Breakable' => { -alias => { break => 'break_bone' } },
265 'Breakdancer' => { -alias => { break => 'break_dance' } };
267 However, aliasing a method simply makes a I<copy> of the method with
268 the new name. We also need to exclude the original name:
270 with 'Breakable' => {
271 -alias => { break => 'break_bone' },
272 -excludes => 'break',
275 -alias => { break => 'break_dance' },
276 -excludes => 'break',
279 The excludes parameter prevents the C<break> method from being composed
280 into the C<FragileDancer> class, so we don't have a conflict. This
281 means that C<FragileDancer> does not need to implement its own
284 This is useful, but it's worth noting that this breaks the contract
285 implicit in consuming a role. Our C<FragileDancer> class does both the
286 C<Breakable> and C<BreakDancer>, but does not provide a C<break>
287 method. If some API expects an object that does one of those roles, it
288 probably expects it to implement that method.
290 In some use cases we might alias and exclude methods from roles, but
291 then provide a method of the same name in the class itself.
293 Also see L<Moose::Cookbook::Roles::Recipe2> for an example.
295 =head1 ROLE EXCLUSION
297 A role can say that it cannot be combined with some other role. This
298 should be used with great caution, since it limits the re-usability of
305 excludes 'BreakDancer';
307 =head1 APPLYING ROLES
309 A role can be applied to a class or an instance in other ways besides
310 using the 'with' syntax.
312 To apply a role to a class, use L<Moose::Util> and the 'apply_all_roles'
313 function. If you apply the role to a class, it will affect all objects of that
314 class. You can't apply a role to a class if it has been made immutable. In
315 some circumstances it may make sense to make the class mutable, apply the role,
316 then make the class immutable again.
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;
325 Do not apply roles to classes that have immutable subclasses, since that
326 will invalidate the metadata of the subclasses.
328 If you want the role to be applied only to a particular instance and not to the
329 class, you can apply the roles to the instance instead of the class's meta:
331 Moose::Util::apply_all_roles($instance, ('MyApp::SomeRole'));
333 Or you can use the role's meta object:
335 MyApp::SomeRole->meta->apply($instance);
337 The mutable/immutable state is not relevant to roles applied to instances.
338 See L<Moose::Role> and L<Moose::Util> for more details and
339 L<Moose::Cookbook::Roles::Recipe3> for a more developed example.
343 Dave Rolsky E<lt>autarch@urth.orgE<gt>
345 =head1 COPYRIGHT AND LICENSE
347 Copyright 2009 by Infinity Interactive, Inc.
349 L<http://www.iinteractive.com>
351 This library is free software; you can redistribute it and/or modify
352 it under the same terms as Perl itself.