1 package Moose::Cookbook::Roles::ApplicationToInstance;
3 # ABSTRACT: Applying a role to an object instance
12 # Not in the recipe, but needed for writing tests.
26 predicate => 'has_work',
34 package MyApp::Role::Job::Manager;
36 use List::Util qw( first );
42 isa => 'ArrayRef[Employee]',
49 my $employee = first { !$_->has_work } @{ $self->employees };
51 die 'All my employees have work to do!' unless $employee;
53 $employee->work($work);
58 my $lisa = Employee->new( name => 'Lisa' );
59 MyApp::Role::Job::Manager->meta->apply($lisa);
61 my $homer = Employee->new( name => 'Homer' );
62 my $bart = Employee->new( name => 'Bart' );
63 my $marge = Employee->new( name => 'Marge' );
65 $lisa->employees( [ $homer, $bart, $marge ] );
66 $lisa->assign_work('mow the lawn');
70 In this recipe, we show how a role can be applied to an object. In
71 this specific case, we are giving an employee managerial
74 Applying a role to an object is simple. The L<Moose::Meta::Role>
75 object provides an C<apply> method. This method will do the right
76 thing when given an object instance.
78 MyApp::Role::Job::Manager->meta->apply($lisa);
80 We could also use the C<apply_all_roles> function from L<Moose::Util>.
82 apply_all_roles( $person, MyApp::Role::Job::Manager->meta );
84 The main advantage of using C<apply_all_roles> is that it can be used
85 to apply more than one role at a time.
87 We could also pass parameters to the role we're applying:
89 MyApp::Role::Job::Manager->meta->apply(
91 -alias => { assign_work => 'get_off_your_lazy_behind' },
94 We saw examples of how method exclusion and alias working in
95 L<Moose::Cookbook::Roles::Restartable_AdvancedComposition>.
99 Applying a role to an object instance is a useful tool for adding
100 behavior to existing objects. In our example, it is effective used to
103 It can also be useful as a sort of controlled monkey-patching for
104 existing code, particularly non-Moose code. For example, you could
105 create a debugging role and apply it to an object at runtime.
110 my $lisa = Employee->new( name => 'Lisa' );
111 MyApp::Role::Job::Manager->meta->apply($lisa);
113 my $homer = Employee->new( name => 'Homer' );
114 my $bart = Employee->new( name => 'Bart' );
115 my $marge = Employee->new( name => 'Marge' );
117 $lisa->employees( [ $homer, $bart, $marge ] );
118 $lisa->assign_work('mow the lawn');
120 ok( $lisa->does('MyApp::Role::Job::Manager'),
121 'lisa now does the manager role' );
123 is( $homer->work, 'mow the lawn',
124 'homer was assigned a task by lisa' );