The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

mixin - Mix-in inheritance, an alternative to multiple inheritance

SYNOPSIS

  package Dog;
  sub speak { print "Bark!\n" }
  sub new { my $class = shift;  bless {}, $class }

  package Dog::Small;
  use base 'Dog';
  sub speak { print "Yip!\n"; }

  package Dog::Retriever;
  use mixin::with 'Dog';
  sub fetch { print "Get your own stinking $_[1]\n" }

  package Dog::Small::Retriever;
  use base 'Dog::Small';
  use mixin 'Dog::Retriever';

  my $small_retriever = Dog::Small::Retriever->new;
  $small_retriever->speak;          # Yip!
  $small_retriever->fetch('ball');  # Get your own stinking ball

DESCRIPTION

Mixin inheritance is an alternative to the usual multiple-inheritance and solves the problem of knowing which parent will be called. It also solves a number of tricky problems like diamond inheritence.

The idea is to solve the same sets of problems which MI solves without the problems of MI.

Using a mixin class.

There are two steps to using a mixin-class.

First, make sure you are inherited from the class with which the mixin-class is to be mixed.

  package Dog::Small::Retriever;
  use base 'Dog::Small';

Since Dog::Small isa Dog, that does it. Then simply mixin the new functionality

  use mixin 'Dog::Retriever';

and now you can use fetch().

AUTHOR

Michael G Schwern <schwern@pobox.com>