Search code examples
perlmojolicious

Structuring a Mojolicious Lite app


I really like the fact that with Mojolicious::Lite I have an overview of routes in one file like this.

get '/foo/#bar' => sub {
     my $c = shift;
     ...;
};

get '/baz/#foo' => sub {
     my $c = shift;
     ...;
};

However in some cases the subs in the file grow too long and complex, and I'd like to split them off, while still keeping the Lite approach.

What's the best way to do that? Is it by creating controllers like in a full Mojolicious app, or should I create helpers in separate modules, and use them?

I can't find pointers to this in the docs.


Solution

  • Having hit something similar, and assuming you're wanting to keep Mojolicious::Lite - the easy solution is to 'outsource' subroutines into packages/modules, that you then use.

    You don't need to do anything particularly special though - with Mojolicious::Lite you need 'helpers' which are basically a way of designating subroutines.

    You can skip that, and create a separate module that just has subroutines defined that you import.

    E.g.

    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    package ExtraStuff;
    
    
    sub generate_a_value {
         return 4; # generated by random dice roll, so guaranteed to be fair and random
     }
    
    1; 
    

    Then just use that in your Mojolicious app.

    Works quite nicely for 'config' type stuff too, especially if you're reusing it.

    I wouldn't suggest doing it for direct HTML generation - Mojolicious already handles that for you, and probably better - but rather just 'outsourcing' stuff that you might be doing via helpers instead anyway.