1 package Moose::Cookbook::Basics::Recipe11;
3 # ABSTRACT: Extending a non-Moose base class
14 'DateTime::Calendar::Mayan' => '0',
24 extends qw( DateTime Moose::Object );
26 use DateTime::Calendar::Mayan;
30 isa => 'DateTime::Calendar::Mayan',
33 builder => '_build_mayan_date',
34 clearer => '_clear_mayan_date',
35 predicate => 'has_mayan_date',
41 my $obj = $class->SUPER::new(@_);
43 return $class->meta->new_object(
50 $_[0]->_clear_mayan_date;
53 sub _build_mayan_date {
54 DateTime::Calendar::Mayan->from_object( object => $_[0] );
59 This recipe demonstrates how to use Moose to subclass a parent which
60 is not Moose based. This recipe only works if the parent class uses a
61 blessed hash reference for object instances. If your parent is doing
62 something funkier, you should check out L<MooseX::InsideOut>.
64 You might also want to check out L<MooseX::NonMoose>, which does all
65 the grunt work for you.
67 There are a couple pieces worth noting:
70 extends qw( DateTime Moose::Object );
72 First, we C<use Moose> just like we always do. This lets us declare
73 attributes and use all the Moose sugar to which we are accustomed.
75 The C<extends> declaration explicitly include L<Moose::Object> as well
76 as L<DateTime>. This lets us use methods which are provided by
77 L<Moose::Object>, like C<does>.
79 The constructor demonstrates a particular hack/pattern (hacktern?) for
80 working with non-Moose parent classes:
85 my $obj = $class->SUPER::new(@_);
87 return $class->meta->new_object(
93 We explicitly call C<< $class->meta->new_object >> and pass the
94 already-created object in the C<__INSTANCE__> key. Internally, Moose
95 will take the existing object and initialize any attributes defined in
98 The C<after> modifier works just like we'd expect. The fact that
99 C<set> is defined in our non-Moose parent does not matter.
103 Moose can play nice with non-Moose classes when you follow the pattern
104 shown here. Your subclass has access to all the power of Moose,
105 including attribute declaration, method modifiers, type constraints
106 (for new attributes), and roles.
108 However, you won't be able to easily override a parent's "attributes",
109 since they're not Moose attributes. Nor will you be able to inline a
110 constructor, since you need to explicitly use the metaclass's object
115 my $dt = My::DateTime->new( year => 1970, month => 2, day => 24 );
117 can_ok( $dt, 'mayan_date' );
118 isa_ok( $dt->mayan_date, 'DateTime::Calendar::Mayan' );
119 is( $dt->mayan_date->date, '12.17.16.9.19', 'got expected mayan date' );
121 $dt->set( year => 2009 );
122 ok( ! $dt->has_mayan_date, 'mayan_date is cleared after call to ->set' );