开发者

Utils in Catalyst (Perl)

开发者 https://www.devze.com 2023-02-27 02:16 出处:网络
Where should I place functions like, for example, sum_it_all() in Catalyst project? It\'s not a model, that\'s nothing about data, it\'s not a controller because it doesn\'t ask the web-request. It\'

Where should I place functions like, for example, sum_it_all() in Catalyst project?

It's not a model, that's nothing about data, it's not a controller because it doesn't ask the web-request. It's 开发者_如何学运维just a simple function and I want it to be accessible in all my controllers.

Now I use Model/Utils.pm and $c->model("utils")->sum_it_all(), but it seems to be really ridiculous.


If you need this functions in a Catalyst Controller, just embed it in the controller where you need it. If you need the same function in several Controller. Create a new Module that contains all your functions. If your Project is named "Foo", then create for example "Foo::Helpers".

In every controller where you need some functions from your helper just import them "use Foo::Helper qw(sum)"

Look at Sub::Exporter for exporting functions.


If it's nothing Catalyst specific, just use it how you would outside the Catalyst context. I'd recommend Sub-Exporter.

The $ctx->model(...) is meant for accessing a layer (::Model::) that is basically a "glue" between Catalyst and your business/model logic. If you don't need any glue (automatic configuration and component inflation for easier access is a common use-case), you can abstract it away as in every Perl application.


I recommend you simply add that function and other useful ones as a Catalyst Plugin and you can access it using the syntax $c->sum_it_all() (see sample plugin below)

========Example custom Plugin====

package Catalyst::Plugin::HelpUtils;
use strict;
use warnings;
our $VERSION = '1.0';

=head1 NAME

Catalyst::Plugin::HelpUtils


=head1 SYNOPSIS

    use Catalyst qw/
    Helputils
    /;

    To use any of the utilities in this plugin e.g:
    $c->sum_it_all()    


=cut

sub sum_it_all{
    my @items = @_;
    my $result = 0;
    foreach(@items) {
        $result += $_;
    }
    return $result;
}


1;


I have set of functions in Utils.pm Helper package, through catalyst I want to access all the methods using $c->utils accessor.

For Eg:

package Utils

sub method1 {
}

sub method2 {
}

In catalyst, I would like to call method1 using $c->utils->method1(<params>) or $c->utils->method2(<params>)

Please let me know the best way to accomplish this.

0

精彩评论

暂无评论...
验证码 换一张
取 消