Let's say that I want to write a Mixin module that adds the method frobnicate() to a given class Foo:
package Foo; use Mixin qw(frobnicate); sub new { bless {}, shift; } package main; my $foo = Foo->new(); $foo->frobnicate();
The Mixin.pm implementation would then look something like this:
package Mixin; use base 'Exporter'; our @EXPORT_OK = qw(frobnicate); sub frobnicate { print "frobnicating!\n"; }
Now this works ok until I want to add another internal method to the mixin and call it in the same way:
package Mixin; use base 'Exporter'; our @EXPORT_OK = qw(frobnicate); sub frobnicate { my($self) = @_; $self->frobnerize(); } sub frobnerize { my($self) = @_; print "frobnerizing!\n"; } 1;
This will cause $foo->frobnicate() to fail, because frobnerize() isn't known to the object:
Can't locate object method "frobnerize" via package "Foo" at Mixin.pm line 9.
I could call frobnerize($self, ...) instead, but I'd like to use the object syntax for various reasons. Also, I could add frobnerize() in the class extended by the Mixin, like
use Mixin qw(frobnicate frobnerize);
(after adding frobnerize to the EXPORTS_OK array) but that would break the encapsulation, as the main program doesn't care about the internal implementation of Foo's frobnicate(). Or, if I could tell Exporter to use both EXPORTS_OK (frobnicate) and EXPORTS (frobnerize), exporting frobnicate() by request and frobnerize() by default, that would somehow work, although Exporter doesn't seem to support it, and it would, again, break the encapsulation. Better ideas, anyone?

In reply to How to write a Mixin without Exporter mess? by saintmike

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.