6 Moose::Cookbook::Roles::Recipe3 - Applying a role to an object instance
10 package MyApp::Role::Job::Manager;
12 use List::Util qw( first );
18 isa => 'ArrayRef[Employee]',
25 my $employee = first { !$_->has_work } @{ $self->employees };
27 die 'All my employees have work to do!' unless $employee;
29 $employee->assign_work($work);
34 my $lisa = Employee->new( name => 'Lisa' );
35 MyApp::Role::Job::Manager->meta->apply($lisa);
37 my $homer = Employee->new( name => 'Homer' );
38 my $bart = Employee->new( name => 'Bart' );
39 my $marge = Employee->new( name => 'Marge' );
41 $lisa->employees( [ $homer, $bart, $marge ] );
42 $lisa->assign_work('mow the lawn');
46 In this recipe, we show how a role can be applied to an object. In
47 this specific case, we are giving an employee managerial
50 Applying a role to an object is simple. The L<Moose::Meta::Role>
51 object provides an C<apply> method. This method will do the right
52 thing when given an object instance.
54 MyApp::Role::Job::Manager->meta->apply($lisa);
56 We could also use the C<apply_all_roles> function from L<Moose::Util>.
58 apply_all_roles( $person, MyApp::Role::Job::Manager->meta );
60 The main advantage of using C<apply_all_roles> is that it can be used
61 to apply more than one role at a time.
63 We could also pass parameters to the role we're applying:
65 MyApp::Role::Job::Manager->meta->apply(
67 alias => { assign_work => 'get_off_your_lazy_behind' },
70 We saw examples of how method exclusion and alias working in L<roles
71 recipe 2|Moose::Cookbook::Roles::Recipe2>.
75 Applying a role to an object instance is a useful tool for adding
76 behavior to existing objects. In our example, it is effective used to
79 It can also be useful as a sort of controlled monkey-patching for
80 existing code, particularly non-Moose code. For example, you could
81 create a debugging role and apply it to an object at runtime.
85 Dave Rolsky E<lt>autarch@urth.orgE<gt>
87 =head1 COPYRIGHT AND LICENSE
89 Copyright 2006-2009 by Infinity Interactive, Inc.
91 L<http://www.iinteractive.com>
93 This library is free software; you can redistribute it and/or modify
94 it under the same terms as Perl itself.