8 'DateTime::Calendar::Mayan' => '0',
15 Moose::Cookbook::Basics::Recipe11 - Extending a non-Moose base class
22 extends qw( DateTime Moose::Object );
24 use DateTime::Calendar::Mayan;
28 isa => 'DateTime::Calendar::Mayan',
31 builder => '_build_mayan_date',
32 clearer => '_clear_mayan_date',
33 predicate => 'has_mayan_date',
39 my $obj = $class->SUPER::new(@_);
41 return $class->meta->new_object(
48 $_[0]->_clear_mayan_date;
51 sub _build_mayan_date {
52 DateTime::Calendar::Mayan->from_object( object => $_[0] );
57 This recipe demonstrates how to use Moose to subclass a parent which
58 is not Moose based. This recipe only works if the parent class uses a
59 blessed hash reference for object instances. If your parent is doing
60 something funkier, you should check out L<MooseX::InsideOut>.
62 You might also want to check out L<MooseX::NonMoose>, which does all
63 the grunt work for you.
65 There are a couple pieces worth noting:
68 extends qw( DateTime Moose::Object );
70 First, we C<use Moose> just like we always do. This lets us declare
71 attributes and use all the Moose sugar to which we are accustomed.
73 The C<extends> declaration explicitly include L<Moose::Object> as well
74 as L<DateTime>. This lets us use methods which are provided by
75 L<Moose::Object>, like C<does>.
77 The constructor demonstrates a particular hack/pattern (hacktern?) for
78 working with non-Moose parent classes:
83 my $obj = $class->SUPER::new(@_);
85 return $class->meta->new_object(
91 We explicitly call C<< $class->meta->new_object >> and pass the
92 already-created object in the C<__INSTANCE__> key. Internally, Moose
93 will take the existing object and initialize any attributes defined in
96 The C<after> modifier works just like we'd expect. The fact that
97 C<set> is defined in our non-Moose parent does not matter.
101 Moose can play nice with non-Moose classes when you follow the pattern
102 shown here. Your subclass has access to all the power of Moose,
103 including attribute declaration, method modifiers, type constraints
104 (for new attributes), and roles.
106 However, you won't be able to easily override a parent's "attributes",
107 since they're not Moose attributes. Nor will you be able to inline a
108 constructor, since you need to explicitly use the metaclass's object
113 Dave Rolsky E<lt>autarch@urth.orgE<gt>
115 =head1 COPYRIGHT AND LICENSE
117 Copyright 2009-2010 by Infinity Interactive, Inc.
119 L<http://www.iinteractive.com>
121 This library is free software; you can redistribute it and/or modify
122 it under the same terms as Perl itself.
126 my $dt = My::DateTime->new( year => 1970, month => 2, day => 24 );
128 can_ok( $dt, 'mayan_date' );
129 isa_ok( $dt->mayan_date, 'DateTime::Calendar::Mayan' );
130 is( $dt->mayan_date->date, '12.17.16.9.19', 'got expected mayan date' );
132 $dt->set( year => 2009 );
133 ok( ! $dt->has_mayan_date, 'mayan_date is cleared after call to ->set' );