Commit | Line | Data |
d5e84b86 |
1 | |
2 | =pod |
3 | |
4 | =head1 NAME |
5 | |
c8d5f1e1 |
6 | Moose::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 | |
32 | Often you find that you want to share some behavior between all your |
33 | classes. One way to do that is to make a base class and simply add |
34 | C<S<extends 'MyApp::Base'>> to every class in your |
35 | application. However, that can get tedious. Instead, you can simply |
36 | create your Moose-alike module that sets the base object class to |
37 | C<MyApp::Base> for you. |
38 | |
39 | Then, instead of writing C<S<use Moose>> you can write C<S<use |
40 | MyApp::UseMyBase>>. |
41 | |
42 | In this particular example, our base class issues some debugging |
43 | output every time a new object is created, but you can surely think of |
44 | some more interesting things to do with your own base class. |
45 | |
554b7648 |
46 | This all works because of the magic of L<Moose::Exporter>. When we |
aedcb7d9 |
47 | call C<< Moose::Exporter->setup_import_methods( also => 'Moose' ) >> |
554b7648 |
48 | it 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 | |
51 | The C<import> method that gets created will call our C<init_meta> |
52 | method, passing it C<< for_caller => $caller >> as its arguments. The |
53 | C<$caller> is set to the class that actually imported us in the first |
54 | place. |
55 | |
56 | See the L<Moose::Exporter> docs for more details on its API. |
57 | |
58 | =head1 USING MyApp::UseMyBase |
59 | |
60 | To actually use our new base class, we simply use C<MyApp::UseMyBase> |
61 | I<instead> of C<Moose>. We get all the Moose sugar plus our new base |
62 | class. |
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 | |
74 | Dave Rolsky E<lt>autarch@urth.orgE<gt> |
75 | |
76 | =head1 COPYRIGHT AND LICENSE |
77 | |
78 | Copyright 2006-2008 by Infinity Interactive, Inc. |
79 | |
80 | L<http://www.iinteractive.com> |
81 | |
82 | This library is free software; you can redistribute it and/or modify |
83 | it under the same terms as Perl itself. |
84 | |
85 | =cut |