renamed some recipes in prep for adding extension intro
[gitmo/Moose.git] / lib / Moose / Cookbook / Extending / Recipe3.pod
CommitLineData
d5e84b86 1
2=pod
3
4=head1 NAME
5
6Moose::Cookbook::Extending::Recipe1 - Providing an alternate base object class
7
8=head1 SYNOPSIS
9
10 package MyApp::Base;
11 use Moose;
12
13 extends 'Moose::Object';
14
15 before 'new' => sub { warn "Making a new " . $_[0] };
16
17 no Moose;
18
19 package MyApp::UseMyBase;
20 use Moose ();
554b7648 21 use Moose::Exporter;
d5e84b86 22
aedcb7d9 23 Moose::Exporter->setup_import_methods( also => 'Moose' );
d5e84b86 24
554b7648 25 sub init_meta {
26 shift;
27 Moose->init_meta( @_, base_class => 'MyApp::Object' );
d5e84b86 28 }
29
30=head1 DESCRIPTION
31
32Often you find that you want to share some behavior between all your
33classes. One way to do that is to make a base class and simply add
34C<S<extends 'MyApp::Base'>> to every class in your
35application. However, that can get tedious. Instead, you can simply
36create your Moose-alike module that sets the base object class to
37C<MyApp::Base> for you.
38
39Then, instead of writing C<S<use Moose>> you can write C<S<use
40MyApp::UseMyBase>>.
41
42In this particular example, our base class issues some debugging
43output every time a new object is created, but you can surely think of
44some more interesting things to do with your own base class.
45
554b7648 46This all works because of the magic of L<Moose::Exporter>. When we
aedcb7d9 47call C<< Moose::Exporter->setup_import_methods( also => 'Moose' ) >>
554b7648 48it builds an C<import> and C<unimport> method for you. The C<< also =>
49'Moose' >> bit says that we want to export everything that Moose does.
50
51The C<import> method that gets created will call our C<init_meta>
52method, passing it C<< for_caller => $caller >> as its arguments. The
53C<$caller> is set to the class that actually imported us in the first
54place.
55
56See the L<Moose::Exporter> docs for more details on its API.
57
58=head1 USING MyApp::UseMyBase
59
60To actually use our new base class, we simply use C<MyApp::UseMyBase>
61I<instead> of C<Moose>. We get all the Moose sugar plus our new base
62class.
63
64 package Foo;
65
66 use MyApp::UseMyBase;
67
68 has 'size' => ( is => 'rw' );
69
70 no MyApp::UseMyBase;
71
d5e84b86 72=head1 AUTHOR
73
74Dave Rolsky E<lt>autarch@urth.orgE<gt>
75
76=head1 COPYRIGHT AND LICENSE
77
78Copyright 2006-2008 by Infinity Interactive, Inc.
79
80L<http://www.iinteractive.com>
81
82This library is free software; you can redistribute it and/or modify
83it under the same terms as Perl itself.
84
85=cut