8fff44c50e6872b535a31ea74deba491cdb25e48
[gitmo/Moose.git] / lib / Moose / Cookbook / Extending / Recipe2.pod
1
2 =pod
3
4 =begin testing-SETUP
5
6 BEGIN {
7     eval 'use Test::Output;';
8     if ($@) {
9         diag 'Test::Output is required for this test';
10         ok(1);
11         exit 0;
12     }
13 }
14
15 =end testing-SETUP
16
17 =head1 NAME
18
19 Moose::Cookbook::Extending::Recipe2 - Providing a role for the base object class
20
21 =head1 SYNOPSIS
22
23   package MooseX::Debugging;
24
25   use Moose::Exporter;
26
27   Moose::Exporter->setup_import_methods(
28       base_class_roles => ['MooseX::Debugging::Role::Object'],
29   );
30
31   package MooseX::Debugging::Role::Object;
32
33   use Moose::Role;
34
35   after 'BUILDALL' => sub {
36       my $self = shift;
37
38       warn "Made a new " . ( ref $self ) . " object\n";
39   };
40
41 =head1 DESCRIPTION
42
43 In this example, we provide a role for the base object class that adds
44 some simple debugging output. Every time an object is created, it
45 spits out a warning saying what type of object it was.
46
47 Obviously, a real debugging role would do something more interesting,
48 but this recipe is all about how we apply that role.
49
50 In this case, with the combination of L<Moose::Exporter> and
51 L<Moose::Util::MetaRole>, we ensure that when a module does C<S<use
52 MooseX::Debugging>>, it automatically gets the debugging role applied
53 to its base object class.
54
55 There are a few pieces of code worth looking at more closely.
56
57   Moose::Exporter->setup_import_methods(
58       base_class_roles => ['MooseX::Debugging::Role::Object'],
59   );
60
61 This creates an C<import> method in the C<MooseX::Debugging> package. Since we
62 are not actually exporting anything, we do not pass C<setup_import_methods>
63 any parameters related to exports, but we need to have an C<import> method to
64 ensure that our C<init_meta> method is called. The C<init_meta> is created by
65 C<setup_import_methods> for us, since we passed the C<base_class_roles>
66 parameter. The generated C<init_meta> will in turn call
67 L<Moose::Util::MetaRole::apply_base_class_roles|Moose::Util::MetaRole/apply_base_class_roles>.
68
69 =head1 AUTHOR
70
71 Dave Rolsky E<lt>autarch@urth.orgE<gt>
72
73 =head1 COPYRIGHT AND LICENSE
74
75 Copyright 2009 by Infinity Interactive, Inc.
76
77 L<http://www.iinteractive.com>
78
79 This library is free software; you can redistribute it and/or modify
80 it under the same terms as Perl itself.
81
82 =begin testing
83
84 {
85     package Debugged;
86
87     use Moose;
88     MooseX::Debugging->import;
89 }
90
91 stderr_is(
92     sub { Debugged->new },
93     "Made a new Debugged object\n",
94     'got expected output from debugging role'
95 );
96
97 =end testing
98
99 =cut