wrote roles recipe 3 - applying a role to an object instance
[gitmo/Moose.git] / lib / Moose / Cookbook / Roles / Recipe3.pod
1
2 =pod
3
4 =head1 NAME
5
6 Moose::Cookbook::Roles::Recipe3 - Applying a role to an object instance
7
8 =head1 SYNOPSIS
9
10   package MyApp::Role::Job::Manager;
11
12   use List::Util qw( first );
13
14   use Moose::Role;
15
16   has 'employees' => (
17       is  => 'rw',
18       isa => 'ArrayRef[Employee]',
19   );
20
21   sub assign_work {
22       my $self = shift;
23       my $work = shift;
24
25       my $employee = first { !$_->has_work } @{ $self->employees };
26
27       die 'All my employees have work to do!' unless $employee;
28
29       $employee->assign_work($work);
30   }
31
32   package main;
33
34   my $lisa = Employee->new( name => 'Lisa' );
35   MyApp::Role::Job::Manager->meta->apply($lisa);
36
37   my $homer = Employee->new( name => 'Homer' );
38   my $bart  = Employee->new( name => 'Bart' );
39   my $marge = Employee->new( name => 'Marge' );
40
41   $lisa->employees( [ $homer, $bart, $marge ] );
42   $lisa->assign_work('mow the lawn');
43
44 =head1 DESCRIPTION
45
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
48 responsibilities.
49
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.
53
54   MyApp::Role::Job::Manager->meta->apply($lisa);
55
56 We could also use the C<apply_all_roles> function from L<Moose::Util>.
57
58   apply_all_roles( $person, MyApp::Role::Job::Manager->meta );
59
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.
62
63 We could also pass parameters to the role we're applying:
64
65   MyApp::Role::Job::Manager->meta->apply(
66       $lisa,
67       alias => { assign_work => 'get_off_your_lazy_behind' },
68   );
69
70 We saw examples of how method exclusion and alias working in L<roles
71 recipe 2|Moose::Cookbook::Roles::Recipe2>.
72
73 =head1 CONCLUSION
74
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
77 model a promotion.
78
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.
82
83 =head1 AUTHOR
84
85 Dave Rolsky E<lt>autarch@urth.orgE<gt>
86
87 =head1 COPYRIGHT AND LICENSE
88
89 Copyright 2006-2009 by Infinity Interactive, Inc.
90
91 L<http://www.iinteractive.com>
92
93 This library is free software; you can redistribute it and/or modify
94 it under the same terms as Perl itself.
95
96 =cut