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
| |- MyApp.pm # Application class
| +- MyApp # Application namespace
| +- Controller # Controller namespace
| +- Example.pm # 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
the MyApp.pm 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 > user.pm
I generally follow this pattern so if my url is /user/lookup
i'll have a route file called Route/user.pm that will handle all my /user routes.
Here is what the plugin looks like
under lib/MyApp/route/user.pm
package MyApp::Route::User;
use Mojo::Base 'Mojolicious::Plugin', -signatures;
sub register ($self, $app, $r) {
$r->get('/user/lookup')->to('user#lookup');
}
1;
Now to add it into the MyApp.pm under lib.
my $r = $self->routes; #this should be somewhere already in the pm file.
$self->plugin('MyApp::Route::User', $r);
This removes tons of lines in the MyApp.pm and makes it easy to find the routes when needed to be worked on.
Top comments (0)