6 Moose::Cookbook::Extending::Recipe3 - Providing an alternate base object class
13 extends 'Moose::Object';
15 before 'new' => sub { warn "Making a new " . $_[0] };
19 package MyApp::UseMyBase;
23 Moose::Exporter->setup_import_methods( also => 'Moose' );
27 Moose->init_meta( @_, base_class => 'MyApp::Object' );
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.
39 Then, instead of writing C<S<use Moose>> you can write C<S<use
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.
46 This all works because of the magic of L<Moose::Exporter>. When we
47 call C<< Moose::Exporter->setup_import_methods( also => 'Moose' ) >>
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.
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
56 See the L<Moose::Exporter> docs for more details on its API.
58 =head1 USING MyApp::UseMyBase
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
68 has 'size' => ( is => 'rw' );
74 Dave Rolsky E<lt>autarch@urth.orgE<gt>
76 =head1 COPYRIGHT AND LICENSE
78 Copyright 2006-2008 by Infinity Interactive, Inc.
80 L<http://www.iinteractive.com>
82 This library is free software; you can redistribute it and/or modify
83 it under the same terms as Perl itself.