Search code examples
perlmojolicious

Mojolicious autostart/init() subroutine


Is there a method/feature to write auto-start subroutine/method for all available Mojolicious routes ?

Maybe an automatic helper, but I don't know how to do it yet.

I think this is useful especially to initialize database connection $self->{dbh} for nearly every available routes, ... so I can write like this:

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

};

instead of:

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

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

P.S: I'm using Mojolicious:Lite, Perl 5.16, SQLite3


Solution

  • I'm not 100% sure I understand your question, helper does almost exactly what you want, but you shouldn't be using the object's hash. Here is how you would use your code:

    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 methods are available for use by all controllers, templates and the main app.