Revised extending recipe 3
[gitmo/Moose.git] / lib / Moose / Cookbook / Extending / Recipe3.pod
CommitLineData
d5e84b86 1
2=pod
3
4=head1 NAME
5
c8d5f1e1 6Moose::Cookbook::Extending::Recipe3 - Providing an alternate base object class
d5e84b86 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
9ac00c2b 32A common extension is to provide an alternate base class. One way to
33do that is to make a C<MyApp::base> and add C<S<extends
34'MyApp::Base'>> to every class in your application. That's pretty
35tedious. Instead, you can create a Moose-alike module that sets the
36base object class to C<MyApp::Base> for you.
d5e84b86 37
38Then, instead of writing C<S<use Moose>> you can write C<S<use
39MyApp::UseMyBase>>.
40
41In this particular example, our base class issues some debugging
9ac00c2b 42output every time a new object is created, but you can think of some
43more interesting things to do with your own base class.
d5e84b86 44
9ac00c2b 45This uses the magic of L<Moose::Exporter>. When we call S<C<<
46Moose::Exporter->setup_import_methods( also => 'Moose' ) >>> it builds
47C<import> and C<unimport> methods for you. The S<C<< also => 'Moose'
48>>> bit says that we want to export everything that Moose does.
554b7648 49
50The C<import> method that gets created will call our C<init_meta>
9ac00c2b 51method, passing it S<C<< for_caller => $caller >>> as its
52arguments. The C<$caller> is set to the class that actually imported
53us in the first place.
554b7648 54
55See the L<Moose::Exporter> docs for more details on its API.
56
57=head1 USING MyApp::UseMyBase
58
59To actually use our new base class, we simply use C<MyApp::UseMyBase>
60I<instead> of C<Moose>. We get all the Moose sugar plus our new base
61class.
62
63 package Foo;
64
65 use MyApp::UseMyBase;
66
67 has 'size' => ( is => 'rw' );
68
69 no MyApp::UseMyBase;
70
9ac00c2b 71=head1 CONCLUSION
72
73This is an awful lot of magic for a simple base class. You will often
74want to combine a metaclass trait with a base class extension, and
75that's when this technique is useful.
76
d5e84b86 77=head1 AUTHOR
78
79Dave Rolsky E<lt>autarch@urth.orgE<gt>
80
81=head1 COPYRIGHT AND LICENSE
82
2840a3b2 83Copyright 2006-2009 by Infinity Interactive, Inc.
d5e84b86 84
85L<http://www.iinteractive.com>
86
87This library is free software; you can redistribute it and/or modify
88it under the same terms as Perl itself.
89
90=cut