Programming with Moose/Syntax/extends

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Use the extends keyword to clobber the inheritance chain setting only that which you've specified. Extends both eliminates and causes problems and should be used often, but with caution when migrating from Non-Moose to Moose.

Gotcha[edit | edit source]

One thing to look out for when using extends is the use of use base. The CORE module "base" does not clobber (overwrite) the inheritance chain but instead adds to it. Steven the author of Moose identified this as a problem area, even though functionality some times depends on the "problem." Extends forces a linear unless otherwise specified inheritance chain, this means the last module in the chain by definition must either use Moose, or push @ISA,'Moose::Object'. If either of these citera are not met you will get obfuscated errors informing you the keywords (plain Perl5 functions) are not defined.

The directive to use Moose instructs Moose to automagically set up @ISA to inherit from Moose::Object. @ISA is clobbered with the use of extends.

Example[edit | edit source]

module A - module B - module C
  1. A extends B
  2. B extends C
  3. C must either use Moose or use base 'Moose::Object'

Class::Accessor[edit | edit source]

Often the culprit of extends problems is Class::Accessor, or legacy junk as the Moose team refers to it. Class::Accessor is often used in base classes as in the following

use base qw/Class::Accessor/;

BEGIN { Class::Accessor::mk_accessors( qw/ foo bar baz / ) };

This has the result of pushing onto @ISA (the inheritance chain) Class::Accesssor but it still leaves Moose out of the picture. Moose expects Moose::Object to be at the base of the inheritance chain.