In my Catalyst app that I am building I have several subroutines that do essentially the same thing, but they are all in different parts of the app. Is there a central place in Catalyst where I can call the subroutines from anywhere in the app? I'd like to avoid repeating code. Thanks!
3 Answers
Don't know if this is a best practice, but I don't have any problem cluttering up my main module with functions like this. Then they can be easily called from anywhere that has your context object (i.e., anywhere).
package MyApp;
...
sub my_frequently_used_sub {
my ($c, @args) = @_;
...
}
package MyApp::Controller::Foo;
...
sub some_action :Path {
my ($self, $c, @args) = @_;
...
my $result = $c->my_frequently_used_sub();
...
}
If the functions should be available outside of your Catalyst app for example because they are used by your model they should go into a completely standalone module. If they are really Catalyst specific you might want to create private actions you can forward or detach to like a 403 not allowed or 404 not found error page. If they are just normal Perl subs you can put them in the app class as suggested by mob or the Root controller. Can you name some of the functions so we can give you a better solution?