ce05b9fb3c5c2f930ca9f7e05ae60de71bae41a8
[gitmo/Moose.git] / lib / Moose / Cookbook / Extending / Recipe2.pod
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
12   use Moose::Exporter;
13
14   Moose::Exporter->setup_import_methods(
15       base_class_roles => ['MooseX::Debugging::Role::Object'],
16   );
17
18   package MooseX::Debugging::Role::Object;
19
20   use Moose::Role;
21
22   after 'BUILD' => sub {
23       my $self = shift;
24
25       warn "Made a new " . ref $self . " object\n";
26   };
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
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
40 to its base object class.
41
42 There are a few pieces of code worth looking at more closely.
43
44   Moose::Exporter->setup_import_methods(
45       base_class_roles => ['MooseX::Debugging::Role::Object'],
46   );
47
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>.
55
56 =head1 AUTHOR
57
58 Dave Rolsky E<lt>autarch@urth.orgE<gt>
59
60 =head1 COPYRIGHT AND LICENSE
61
62 Copyright 2009 by Infinity Interactive, Inc.
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