documentation for applying roles, specifically to instances
[gitmo/Moose.git] / lib / Moose / Manual / Roles.pod
index 888a238..c2f5df1 100644 (file)
@@ -100,6 +100,8 @@ We could use this same role in a C<Bone> class:
       isa => 'Marrow',
   );
 
+See also L<Moose::Cookbook::Roles::Recipe1> for an example.
+
 =head1 REQUIRED METHODS
 
 As mentioned previously, a role can require that consuming classes
@@ -242,6 +244,14 @@ provide our own C<break> method:
 
   sub break { ... }
 
+A role can be a collection of other roles:
+
+  package Break::Bundle;
+
+  use Moose::Role;
+
+  with ('Breakable', 'Breakdancer');
+
 =head1 METHOD EXCLUSION AND ALIASING
 
 If we want our C<FragileDancer> class to be able to call the methods
@@ -280,6 +290,8 @@ 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.
 
+Also see L<Moose::Cookbook::Roles::Recipe2> for an example.
+
 =head1 ROLE EXCLUSION
 
 A role can say that it cannot be combined with some other role. This
@@ -292,6 +304,40 @@ the role.
 
   excludes 'BreakDancer';
 
+=head1 APPLYING ROLES
+
+A role can be applied to a class or an instance in other ways besides
+using the 'with' syntax.
+
+To apply a role to a class, use L<Moose::Util> and the 'apply_all_roles'
+function. If you apply the role to a class, it will affect all objects of that
+class. You can't apply a role to a class if it has been made immutable. In
+some circumstances it may make sense to make the class mutable, apply the role,
+then make the class immutable again.
+
+   use Moose::Util;
+   ...
+   my $class = 'MyApp::Test';
+   $class->meta->make_mutable;
+   Moose::Util::apply_all_roles($class->meta, ('MyApp::SomeRole'));
+   $class->meta->make_immutable;
+
+Do not apply roles to classes that have immutable subclasses, since that
+will invalidate the metadata of the subclasses.
+
+If you want the role to be applied only to a particular instance and not to the
+class, you can apply the roles to the instance instead of the class's meta:
+
+   Moose::Util::apply_all_roles($instance, ('MyApp::SomeRole'));
+
+Or you can use the role's meta object:
+
+   MyApp::SomeRole->meta->apply($instance);
+
+The mutable/immutable state is not relevant to roles applied to instances. 
+See L<Moose::Role> and L<Moose::Util> for more details and 
+L<Moose::Cookbook::Roles::Recipe3> for a more developed example.
+
 =head1 AUTHOR
 
 Dave Rolsky E<lt>autarch@urth.orgE<gt>