Mojolicious autostart / init()子程序

时间:2013-04-25 15:03:03

标签: perl mojolicious

是否有方法/功能为所有可用的Mojolicious路线编写自动启动子程序/方法?

也许是自动助手,但我不知道该怎么做。

我认为这对于几乎所有可用路由初始化数据库连接$ self-> {dbh}都很有用,所以我可以像这样写:

helper DB => sub { state $dbh = Database->new };

get '/' => sub {
    my $self = shift;
    //$self->{dbh}  // is automatically initialized & shared
};

get '/another_route' => sub {
    my $self = shift;
    //$self->{dbh}  // also initialized & shared

};

而不是:

get '/' => sub {
    my $self = shift;
    $self->{dbh} = init_db();
};

get '/another_route' => sub {
    my $self = shift;
    $self->{dbh} = init_db();
};

P.S:我正在使用Mojolicious:Lite,Perl 5.16,SQLite3

1 个答案:

答案 0 :(得分:3)

我不是100%确定我理解你的问题,helper几乎完全符合你的要求,但你不应该使用对象的哈希。以下是使用代码的方法:

helper db => sub { state $dbh = Database->new };

get '/' => sub {
    my $self = shift;
    $self->db->do_somthing();
};

get '/another_route' => sub {
    my $self = shift;
    my $dbh = $self->db;
    ...
};

helper方法可供所有控制器,模板和主应用程序使用。