Moose::Manual::Roles.3pm

Langue: en

Version: 2009-03-09 (fedora - 06/07/09)

Section: 3 (Bibliothèques de fonctions)

NAME

Moose::Manual::Roles - Roles, an alternative to deep hierarchies and base classes

WHAT IS A ROLE?

A role is something that classes do. Usually, a role encapsulates some piece of behavior or state that can be shared between classes. It is important to understand that roles are not classes. You cannot inherit from a role, and a role cannot be instantiated. We sometimes say that roles are consumed, either by classes or other roles.

Instead, a role is composed into a class. In practical terms, this means that all of the methods and attributes defined in a role are added directly to (we sometimes say ``flattened into'') the class that consumes the role. These attributes and methods then appear as if they were defined in the class itself. A subclass of the consuming class will inherit all of these methods and attributes.

Moose roles are similar to mixins or interfaces in other languages.

Besides defining their own methods and attributes, roles can also require that the consuming class define certain methods of its own. You could have a role that consisted only of a list of required methods, in which case the role would be very much like a Java interface.

A SIMPLE ROLE

Creating a role looks a lot like creating a Moose class:
   package Breakable;
 
   use Moose::Role;
 
   has 'is_broken' => (
       is  => 'rw',
       isa => 'Bool',
   );
 
   sub break {
       my $self = shift;
 
       print "I broke\n";
 
       $self->is_broken(1);
   }
 
 

Except for our use of Moose::Role, this looks just like a class definition with Moose. However, this is not a class, and it cannot be instantiated.

Instead, its attributes and methods will be composed into classes which use the role:

   package Car;
 
   use Moose;
 
   with 'Breakable';
 
   has 'engine' => (
       is  => 'ro',
       isa => 'Engine',
   );
 
 

The "with" function composes roles into a class. Once that is done, the "Car" class has an "is_broken" attribute and a "break" method. The "Car" class also "does('Breakable')":

   my $car = Car->new( engine => Engine->new );
 
   print $car->is_broken ? 'Still working' : 'Busted';
   $car->break;
   print $car->is_broken ? 'Still working' : 'Busted';
 
   $car->does('Breakable'); # true
 
 

This prints:

   Still working
   I broke
   Busted
 
 

We could use this same role in a "Bone" class:

   package Bone;
 
   use Moose;
 
   with 'Breakable';
 
   has 'marrow' => (
       is  => 'ro',
       isa => 'Marrow',
   );
 
 

REQUIRED METHODS

As mentioned previously, a role can require that consuming classes provide one or more methods. Using our "Breakable" example, let's make it require that consuming classes implement their own "break" methods:
   package Breakable;
 
   use Moose::Role;
 
   requires 'break';
 
   has 'is_broken' => (
       is  => 'rw',
       isa => 'Bool',
   );
 
   after 'break' => sub {
       my $self = shift;
 
       $self->is_broken(1);
   };
 
 

If we try to consume this role in a class that does not have a "break" method, we will get an exception.

You can see that we added a method modifier on "break". We want classes that consume this role to implement their own logic for breaking, but we make sure that the "is_broken" attribute is always set to true when "break" is called.

   package Car
 
   use Moose;
 
   with 'Breakable';
 
   has 'engine' => (
       is  => 'ro',
       isa => 'Engine',
   );
 
   sub break {
       my $self = shift;
 
       if ( $self->is_moving ) {
           $self->stop;
       }
   }
 
 

Roles Versus Abstract Base Classes

If you are familiar with the concept of abstract base classes in other languages, you may be tempted to use roles in the same way.

You can define a ``interface-only'' role, one that contains just a list of required methods.

However, any class which consumes this role must implement all of the required methods, either directly or through inheritance from a parent. You cannot delay the method requirement check so that they can be implemented by future subclasses.

Because the role defines the required methods directly, adding a base class to the mix would not achieve anything. We recommend that you simply consume the interface role in each class which implements that interface.

USING METHOD MODIFIERS

Method modifiers and roles are a very powerful combination. Often, a role will combine method modifiers and required methods. We already saw one example with our "Breakable" example.

Method modifiers increase the complexity of roles, because they make the role application order relevant. If a class uses multiple roles, each of which modify the same method, those modifiers will be applied in the same order as the roles are used:

   package MovieCar;
 
   use Moose;
 
   extends 'Car';
 
   with 'Breakable', 'ExplodesOnBreakage';
 
 

Assuming that the new "ExplodesOnBreakage" method also has an "after" modifier on "break", the "after" modifiers will run one after the other. The modifier from "Breakable" will run first, then the one from "ExplodesOnBreakage".

METHOD CONFLICTS

If a class composes multiple roles, and those roles have methods of the same name, we will have a conflict. In that case, the composing class is required to provide its own method of the same name.
   package Breakdances;
 
   use Moose::Role
 
   sub break {
 
   }
 
 

If we compose both "Breakable" and "Breakdancer" in a class, we must provide our own "break" method:

   package FragileDancer;
 
   use Moose;
 
   with 'Breakable', 'Breakdancer';
 
   sub break { ... }
 
 

METHOD EXCLUSION AND ALIASING

If we want our "FragileDancer" class to be able to call the methods from both its roles, we can alias the methods:
   package FragileDancer;
 
   use Moose;
 
   with 'Breakable'   => { alias => { break => 'break_bone' } },
        'Breakdancer' => { alias => { break => 'break_dance' } };
 
 

However, aliasing a method simply makes a copy of the method with the new name. We also need to exclude the original name:

   with 'Breakable' => {
       alias   => { break => 'break_bone' },
       exclude => 'break',
       },
       'Breakdancer' => {
       alias   => { break => 'break_dance' },
       exclude => 'break',
       };
 
 

The exclude parameter prevents the "break" method from being composed into the "FragileDancer" class, so we don't have a conflict. This means that "FragileDancer" does not need to implement its own "break" method.

This is useful, but it's worth noting that this breaks the contract implicit in consuming a role. Our "FragileDancer" class does both the "Breakable" and "BreakDancer", but does not provide a "break" method. If some API expects an object that does one of those roles, it probably expects it to implement that method.

In some use cases we might alias and exclude methods from roles, but then provide a method of the same name in the class itself.

ROLE EXCLUSION

A role can say that it cannot be combined with some other role. This should be used with great caution, since it limits the re-usability of the role.
   package Breakable;
 
   use Moose::Role;
 
   excludes 'BreakDancer';
 
 

AUTHOR

Dave Rolsky <autarch@urth.org> Copyright 2009 by Infinity Interactive, Inc.

<http://www.iinteractive.com>

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.