Commit | Line | Data |
f3ce0579 |
1 | |
2 | =pod |
3 | |
4 | =head1 NAME |
5 | |
6 | Moose::Cookbook::Extending::Recipe2 - Providing a role for the base object class |
7 | |
8 | =head1 SYNOPSIS |
9 | |
10 | package MooseX::Debugging; |
11 | |
f3ce0579 |
12 | use Moose::Exporter; |
f3ce0579 |
13 | |
95056a1e |
14 | Moose::Exporter->setup_import_methods( |
15 | base_class_roles => ['MooseX::Debugging::Role::Object'], |
16 | ); |
f3ce0579 |
17 | |
f3ce0579 |
18 | package MooseX::Debugging::Role::Object; |
19 | |
0df6b748 |
20 | use Moose::Role; |
21 | |
f3ce0579 |
22 | after 'BUILD' => sub { |
23 | my $self = shift; |
24 | |
25 | warn "Made a new " . ref $self . " object\n"; |
6a7e3999 |
26 | }; |
f3ce0579 |
27 | |
28 | =head1 DESCRIPTION |
29 | |
30 | In this example, we provide a role for the base object class that adds |
31 | some simple debugging output. Every time an object is created, it |
32 | spits out a warning saying what type of object it was. |
33 | |
34 | Obviously, a real debugging role would do something more interesting, |
35 | but this recipe is all about how we apply that role. |
36 | |
37 | In this case, with the combination of L<Moose::Exporter> and |
8efdbb91 |
38 | L<Moose::Util::MetaRole>, we ensure that when a module does C<S<use |
39 | MooseX::Debugging>>, it automatically gets the debugging role applied |
f3ce0579 |
40 | to its base object class. |
41 | |
871cda31 |
42 | There are a few pieces of code worth looking at more closely. |
43 | |
95056a1e |
44 | Moose::Exporter->setup_import_methods( |
45 | base_class_roles => ['MooseX::Debugging::Role::Object'], |
46 | ); |
871cda31 |
47 | |
edd82429 |
48 | This creates an C<import> method in the C<MooseX::Debugging> package. Since we |
49 | are not actually exporting anything, we do not pass C<setup_import_methods> |
50 | any parameters related to exports, but we need to have an C<import> method to |
51 | ensure that our C<init_meta> method is called. The C<init_meta> is created by |
52 | C<setup_import_methods> for us, since we passed the C<base_class_roles> |
53 | parameter. The generated C<init_meta> will in turn call |
54 | L<Moose::Util::MetaRole::apply_base_class_roles|Moose::Util::MetaRole/apply_base_class_roles>. |
871cda31 |
55 | |
f3ce0579 |
56 | =head1 AUTHOR |
57 | |
58 | Dave Rolsky E<lt>autarch@urth.orgE<gt> |
59 | |
60 | =head1 COPYRIGHT AND LICENSE |
61 | |
2840a3b2 |
62 | Copyright 2009 by Infinity Interactive, Inc. |
f3ce0579 |
63 | |
64 | L<http://www.iinteractive.com> |
65 | |
66 | This library is free software; you can redistribute it and/or modify |
67 | it under the same terms as Perl itself. |
68 | |
69 | =cut |
70 | |