Search code examples
moose

How to wrap a non-OO module of functions into a moose class


A few month ago I started to use Moose.

There are some non-OO modules I use simply made of related functions. I'd like to use these functions in Moose classes as methods. May be the simplest way doing it is like

#!/usr/bin/env perl

package FuncPack;

sub func_1 {
    print "-> ", __PACKAGE__, "::func_1 called \n";
}

package FuncClass;
use Moose;
use namespace::autoclean;

sub func_1 {
    my $self = shift ;
    return FuncPack::func_1(@_);
}

__PACKAGE__->meta->make_immutable;


package main;

my $obj = FuncClass->new();    
$obj->func_1(); # shall call FuncPack::func_1 

For one function it may be ok, but if you have a lot it's a repeating task and boring. Is there a more clever way to accomplish it ? May be there is something similar to MooseX::NonMoose or MooseX::InsideOut which are for extending non-Moose classes ?

Thanks for advice or hints.


Solution

  • Moose typically doesn't deal with this, wrapping non-OO modules in an OO framework seems a bit odd. However if you have a list of the methods (or can generate one) you could do something like:

    package FuncClass;
    use Moose;
    
    my @list = qw( func_1 func_2 func_3 ... );
    for my $method in @list {
       __PACKAGE__->meta->add_method(
           $method => sub { my $s = shift; FuncPack::$method(@_)  
       });
    }
    

    You may be able to use something like Package::Stash to pull out the list of functions from FuncPack.

    I'm wondering however why you would want to do this to begin with? Your FuncClass will be carrying absolutely no state, and really doesn't serve a purpose other than to add a layer of indirection.