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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.