[Catalyst] More natural access to model?

Tomas Doran bobtfish at bobtfish.net
Tue May 12 12:00:22 GMT 2009


Paweł Tęcza wrote:
> Thank you very much for your response! Is it a way to autogenerate all
> necessary subroutines in a loop or I need define all of them manually?
> They should have very similar body :)

Here is the gross method:

no strict 'refs';
foreach my $name (qw/ method_one method_two /) {
     *{$name} = sub {
         my $self = shift;
         # Your code here
     };
}


I'd instead recommend using Moose to do it for you:

use Moose;
foreach my $name (qw/ method_one method_two /) {
     __PACKAGE__->meta->add_method($name, sub {
         my $self = shift;
         # Your code here
     };
}

This is (a) less icky, and (b) means that your generated code will come 
out nicely in stack traces / error reports, rather than being 'ANON'.

Cheers
t0m



More information about the Catalyst mailing list