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 A common extension is to provide an alternate base class. One way to
33 do 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
35 tedious. Instead, you can create a Moose-alike module that sets the
36 base object class to C<MyApp::Base> for you.
38 Then, instead of writing C<S<use Moose>> you can write C<S<use
41 In this particular example, our base class issues some debugging
42 output every time a new object is created, but you can think of some
43 more interesting things to do with your own base class.
45 This uses the magic of L<Moose::Exporter>. When we call C<<
46 Moose::Exporter->setup_import_methods( also => 'Moose' ) >> it builds
47 C<import> and C<unimport> methods for you. The C<< also => 'Moose' >>
48 bit says that we want to export everything that Moose does.
50 The C<import> method that gets created will call our C<init_meta>
51 method, passing it C<< for_caller => $caller >> as its
52 arguments. The C<$caller> is set to the class that actually imported
53 us in the first place.
55 See the L<Moose::Exporter> docs for more details on its API.
57 =head1 USING MyApp::UseMyBase
59 To actually use our new base class, we simply use C<MyApp::UseMyBase>
60 I<instead> of C<Moose>. We get all the Moose sugar plus our new base
67 has 'size' => ( is => 'rw' );
73 This is an awful lot of magic for a simple base class. You will often
74 want to combine a metaclass trait with a base class extension, and
75 that's when this technique is useful.
79 Dave Rolsky E<lt>autarch@urth.orgE<gt>
81 =head1 COPYRIGHT AND LICENSE
83 Copyright 2006-2009 by Infinity Interactive, Inc.
85 L<http://www.iinteractive.com>
87 This library is free software; you can redistribute it and/or modify
88 it under the same terms as Perl itself.