DEV Community


Posted on

Organizing Mojolicious Routes

Mojolicious is an awesome web framework and I have been developing an app in it for 2 years now.

The basic structure is (taken off the docs - Growing)

myapp                      # Application directory
|- script                  # Script directory
|  +- my_app               # Application script
|- lib                     # Library directory
|  |-             # Application class
|  +- MyApp                # Application namespace
|     +- Controller        # Controller namespace
|        +-     # Controller class
|- my_app.yml              # Configuration file
|- t                       # Test directory
|  +- basic.t              # Random test
|- log                     # Log directory
|  +- development.log      # Development mode log file
|- public                  # Static file directory (served automatically)
|  +- index.html           # Static HTML file
+- templates               # Template directory
   |- layouts              # Template directory for layouts
   |  +- default.html.ep   # Layout template
   +- example              # Template directory for "Example" controller
      +- welcome.html.ep   # Template for "welcome" action
Enter fullscreen mode Exit fullscreen mode

the is the core file that defines routes, app settings and plugins. As I was growing my app, that pm file became very large (200+ lines) with routes and I needed to do something. I remember reading from the devs that its best to use plugins for routes when your project becomes big.

I made a folder and a file under lib called Route >

I generally follow this pattern so if my url is /user/lookup
i'll have a route file called Route/ that will handle all my /user routes.

Here is what the plugin looks like

under lib/MyApp/route/

package MyApp::Route::User;
use Mojo::Base 'Mojolicious::Plugin', -signatures;

sub register ($self, $app, $r) {

Enter fullscreen mode Exit fullscreen mode

Now to add it into the under lib.

my $r = $self->routes; #this should be somewhere already in the pm file.
$self->plugin('MyApp::Route::User', $r);
Enter fullscreen mode Exit fullscreen mode

This removes tons of lines in the and makes it easy to find the routes when needed to be worked on.

Top comments (0)