Mojolic...Growing(3)
okay bestie, buckle up β this is part 1 of 3 of the Mojolicious::Guides::Growing glow-up guide, and we are literally taking a tiny prototype from zero to a structured app. More parts are coming, so don't log off π
β¨
πΈ NAME πΈ
Mojolicious::Guides::Growing - Growing Mojolicious applications π«Ά
β¨ OVERVIEW β¨
This doc walks you through starting a Mojolicious::Lite prototype from scratch and growing it into a well-structured Mojolicious application. The final result is also available as an example application at https://github.com/mojolicious/mojo/tree/main/examples/login. Iconic.
π§ CONCEPTS π§
Essentials every Mojolicious developer should know, periodt.
π Model View Controller π
MVC is a software architectural pattern for graphical user interface programming originating in Smalltalk-80, that separates application logic, presentation and input. It's giving classic.
+------------+ +-------+ +------+
Input -> | Controller | -> | Model | -> | View | -> Output
+------------+ +-------+ +------+
A slightly modified version of the pattern moving some application logic into the controller is the foundation of pretty much every web framework these days, including Mojolicious. The glow-up:
+----------------+ +-------+
Request -> | | <-> | Model |
| | +-------+
| Controller |
| | +-------+
Response <- | | <-> | View |
+----------------+ +-------+
The controller receives a request from a user, passes incoming data to the model and retrieves data from it, which then gets turned into an actual response by the view. But bestie, note that this pattern is just a guideline that most of the time results in cleaner more maintainable code, not a rule that should be followed at all costs.
π¦ REpresentational State Transfer π¦
REST is a software architectural style for distributed hypermedia systems such as the web. While it can be applied to many protocols it is most commonly used with HTTP these days. In REST terms, when you are opening a URL like http://mojolicious.org/foo with your browser, you are basically asking the web server for the HTML representation of the http://mojolicious.org/foo resource. No cap.
+--------+ +--------+
| | -> http://mojolicious.org/foo -> | |
| Client | | Server |
| | <- <html>Mojo rocks!</html> <- | |
+--------+ +--------+
The fundamental idea here is that all resources are uniquely addressable with URLs and every resource can have different representations such as HTML, RSS or JSON. User interface concerns are separated from data storage concerns and all session state is kept client-side. Obsessed.
+---------+ +------------+
| | -> PUT /foo -> | |
| | -> Hello World! -> | |
| | | |
| | <- 201 CREATED <- | |
| | | |
| | -> GET /foo -> | |
| Browser | | Web Server |
| | <- 200 OK <- | |
| | <- Hello World! <- | |
| | | |
| | -> DELETE /foo -> | |
| | | |
| | <- 200 OK <- | |
+---------+ +------------+
While HTTP methods such as PUT, GET and DELETE are not directly part of REST they go well with it and are commonly used to manipulate resources. Iykyk.
π Sessions π
HTTP was designed as a stateless protocol, web servers don't know anything about previous requests, which makes user-friendly login systems tricky. Sessions solve this problem by allowing web applications to keep stateful information across several HTTP requests. Main character energy.
GET /login?user=sebastian&pass=s3cret HTTP/1.1
Host: mojolicious.org
HTTP/1.1 200 OK
Set-Cookie: sessionid=987654321
Content-Length: 10
Hello sebastian.
GET /protected HTTP/1.1
Host: mojolicious.org
Cookie: sessionid=987654321
HTTP/1.1 200 OK
Set-Cookie: sessionid=987654321
Content-Length: 16
Hello again sebastian.
Traditionally all session data was stored on the server-side and only session IDs were exchanged between browser and web server in the form of cookies.
Set-Cookie: session=hmac-sha256(base64(json($session)))
In Mojolicious however we are taking this concept one step further by storing everything JSON serialized and Base64 encoded in HMAC-SHA256 signed, or ChaCha20-Poly1305 encrypted cookies, which is more compatible with the REST philosophy and reduces infrastructure requirements. Slay.
π Test-Driven Development π
TDD is a software development process where the developer starts writing failing test cases that define the desired functionality and then moves on to producing code that passes these tests. There are many advantages such as always having good test coverage and code being designed for testability, which will in turn often prevent future changes from breaking old code. Much of Mojolicious was developed using TDD. Respect.
π PROTOTYPE π
One of the main differences between Mojolicious and other web frameworks is that it also includes Mojolicious::Lite, a micro web framework optimized for rapid prototyping. It's giving fast.
π Differences π
You likely know the feeling, you've got a really cool idea and want to try it as quickly as possible, that's exactly why Mojolicious::Lite applications don't need more than a single file.
myapp.pl # Templates and even static files can be inlined
Full Mojolicious applications on the other hand are much closer to a well organized CPAN distribution to maximize maintainability.
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)
| |-- assets # Static assets created by bundlers
| | `-- *generated assets*
| +- 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
Both application skeletons can be automatically generated with the commands Mojolicious::Command::Author::generate::lite_app and Mojolicious::Command::Author::generate::app.
$ mojo generate lite-app myapp.pl
$ mojo generate app MyApp
Feature-wise both are almost equal, the only real differences are organizational, so each one can be gradually transformed into the other. Cute.
π§ Foundation π§
We start our new application with a single executable Perl script.
$ mkdir myapp
$ cd myapp
$ touch myapp.pl
$ chmod 744 myapp.pl
This will be the foundation for our login manager example application.
#!/usr/bin/env perl
use Mojolicious::Lite -signatures;
get '/' => sub ($c) {
$c->render(text => 'Hello World!');
};
app->start;
The built-in development web server makes working on your application a lot of fun thanks to automatic reloading.
$ morbo ./myapp.pl
Web application available at http://127.0.0.1:3000
Just save your changes and they will be automatically in effect the next time you refresh your browser. Literally magic.
π A bird's-eye view π
It all starts with an HTTP request like this, sent by your browser.
GET / HTTP/1.1
Host: localhost:3000
Once the request has been received by the web server through the event loop, it will be passed on to Mojolicious, where it will be handled in a few simple steps.
- Check if a static file exists that would meet the requirements.
- Try to find a route that would meet the requirements.
- Dispatch the request to this route, usually reaching one or more actions.
- Process the request, maybe generating a response with the renderer.
- Return control to the web server, and if no response has been generated yet, wait for a non-blocking operation to do so through the event loop.
With our application the router would have found an action in step 2, and rendered some text in step 4, resulting in an HTTP response like this being sent back to the browser.
HTTP/1.1 200 OK
Content-Length: 12
Hello World!
π Model π
In Mojolicious we consider web applications simple frontends for existing business logic. That means Mojolicious is by design entirely model layer agnostic, and you just use whatever Perl modules you like most. Periodt.
$ mkdir -p lib/MyApp/Model
$ touch lib/MyApp/Model/Users.pm
$ chmod 644 lib/MyApp/Model/Users.pm
Our login manager will use a plain old Perl module abstracting away all logic related to matching usernames and passwords. The name MyApp::Model::Users is an arbitrary choice, and is simply used to make the separation of concerns more visible.
package MyApp::Model::Users;
use strict;
use warnings;
use experimental qw(signatures);
use Mojo::Util qw(secure_compare);
my $USERS = {
joel => 'las3rs',
marcus => 'lulz',
sebastian => 'secr3t'
};
sub new ($class) { bless {}, $class }
sub check ($self, $user, $pass) {
# Success
return 1 if $USERS->{$user} && secure_compare $USERS->{$user}, $pass;
# Fail
return undef;
}
1;
A simple helper can be registered with the function helper in Mojolicious::Lite to make our model available to all actions and templates.
#!/usr/bin/env perl
use Mojolicious::Lite -signatures;
use lib qw(lib);
use MyApp::Model::Users;
# Helper to lazy initialize and store our model object
helper users => sub { state $users = MyApp::Model::Users->new };
# /?user=sebastian&pass=secr3t
any '/' => sub ($c) {
# Query parameters
my $user = $c->param('user') || '';
my $pass = $c->param('pass') || '';
# Check password
return $c->render(text => "Welcome $user.") if $c->users->check($user, $pass);
# Failed
$c->render(text => 'Wrong username or password.');
};
app->start;
so the method param in Mojolicious::Controller is literally your one-stop shop β it grabs query parameters, POST parameters, file uploads and route placeholders, all at once π«Ά like bestie it does not care where the data came from, it just hands it over.
π§ͺ Testing
okay so in Mojolicious we take testing very seriously and genuinely try to make it a whole pleasant experience, not a chore π
$ mkdir t
$ touch t/login.t
$ chmod 644 t/login.t
Test::Mojo is a scriptable HTTP user agent that was designed specifically for testing, and it comes with so many fun state-of-the-art features β CSS selectors based on Mojo::DOM being one of them β¨
use Test::More;
use Test::Mojo;
# Include application
use Mojo::File qw(curfile);
require(curfile->dirname->sibling('myapp.pl'));
# Allow 302 redirect responses
my $t = Test::Mojo->new;
$t->ua->max_redirects(1);
# Test if the HTML login form exists
$t->get_ok('/')
->status_is(200)
->element_exists('form input[name="user"]')
->element_exists('form input[name="pass"]')
->element_exists('form input[type="submit"]');
# Test login with valid credentials
$t->post_ok('/' => form => {user => 'sebastian', pass => 'secr3t'})
->status_is(200)
->text_like('html body' => qr/Welcome sebastian/);
# Test accessing a protected page
$t->get_ok('/protected')->status_is(200)->text_like('a' => qr/Logout/);
# Test if HTML login form shows up again after logout
$t->get_ok('/logout')
->status_is(200)
->element_exists('form input[name="user"]')
->element_exists('form input[name="pass"]')
->element_exists('form input[type="submit"]');
done_testing();
ngl your application is not passing these tests yet, but from now on you can use them to check your progress π slay.
$ prove -l
$ prove -l t/login.t
$ prove -l -v t/login.t
or, if you're feeling impatient (same), do quick requests right from the command line with Mojolicious::Command::get:
$ ./myapp.pl get /
Wrong username or password.
$ ./myapp.pl get -v '/?user=sebastian&pass=secr3t'
GET /?user=sebastian&pass=secr3t HTTP/1.1
User-Agent: Mojolicious (Perl)
Accept-Encoding: gzip
Content-Length: 0
Host: localhost:59472
HTTP/1.1 200 OK
Date: Sun, 18 Jul 2010 13:09:58 GMT
Server: Mojolicious (Perl)
Content-Length: 12
Content-Type: text/plain
Welcome sebastian.
π State keeping
sessions in Mojolicious pretty much just work out of the box the second you start using the method session in Mojolicious::Controller β there is literally no setup required π but we do suggest setting a more secure passphrase with secrets in Mojolicious:
app->secrets(['Mojolicious rocks']);
this passphrase is used by the HMAC-SHA256 algorithm to make signed cookies tamper resistant, and can be changed at any time to invalidate all existing sessions π
$c->session(user => 'sebastian');
my $user = $c->session('user');
by default, all sessions expire after one hour β° and if you want more control you can use the expiration session value to set an expiration date in seconds from now:
$c->session(expiration => 3600);
and the whole session can be deleted by using the expires session value to set an absolute expiration date in the past ποΈ
$c->session(expires => 1);
for data that should only be visible on the next request β like a confirmation message after a 302 redirect performed with redirect_to in Mojolicious::Plugin::DefaultHelpers β you can use the flash, accessible through flash in Mojolicious::Plugin::DefaultHelpers π¦
$c->flash(message => 'Everything is fine.');
$c->redirect_to('goodbye');
just remember bestie: all session data gets serialized with Mojo::JSON and stored in HMAC-SHA256 signed cookies, which usually have a 4096 byte (4KiB) limit, depending on browser π
π Final prototype
a final myapp.pl prototype that passes all of the tests above could look like this:
#!/usr/bin/env perl
use Mojolicious::Lite -signatures;
use lib qw(lib);
use MyApp::Model::Users;
# Make signed cookies tamper resistant
app->secrets(['Mojolicious rocks']);
helper users => sub { state $users = MyApp::Model::Users->new };
# Main login action
any '/' => sub ($c) {
# Query or POST parameters
my $user = $c->param('user') || '';
my $pass = $c->param('pass') || '';
# Check password and render "index.html.ep" if necessary
return $c->render unless $c->users->check($user, $pass);
# Store username in session
$c->session(user => $user);
# Store a friendly message for the next page in flash
$c->flash(message => 'Thanks for logging in.');
# Redirect to protected page with a 302 response
$c->redirect_to('protected');
} => 'index';
# Make sure user is logged in for actions in this group
group {
under sub ($c) {
# Redirect to main page with a 302 response if user is not logged in
return 1 if $c->session('user');
$c->redirect_to('index');
return undef;
};
# A protected page auto rendering "protected.html.ep"
get '/protected';
};
# Logout action
get '/logout' => sub ($c) {
# Expire and in turn clear session automatically
$c->session(expires => 1);
# Redirect to main page with a 302 response
$c->redirect_to('index');
};
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
%= form_for index => begin
% if (param 'user') {
<b>Wrong name or password, please try again.</b><br>
% }
Name:<br>
%= text_field 'user'
<br>Password:<br>
%= password_field 'pass'
<br>
%= submit_button 'Login'
% end
@@ protected.html.ep
% layout 'default';
% if (my $msg = flash 'message') {
<b><%= $msg %></b><br>
% }
Welcome <%= session 'user' %>.<br>
%= link_to Logout => 'logout'
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title>Login Manager</title></head>
<body><%= content %></body>
</html>
and the directory structure should be looking like this now ποΈ
myapp
|- myapp.pl
|- lib
| +- MyApp
| +- Model
| +- Users.pm
+- t
+- login.t
our templates are using quite a few features of the renderer, and Mojolicious::Guides::Rendering explains them all in great detail π
π WELL-STRUCTURED APPLICATION π
okay so bestie, Mojolicious is flexible af, which means the actual growing process has a bunch of variations β but this is your good overview of the possibilities, fr fr. π¦
π Inflating templates π
So every template and static file that's inlined in the DATA section? They can be automatically turned into separate files in the templates and public directories with Mojolicious::Command::Author::inflate. The command is literally:
$ ./myapp.pl inflate
And those directories have a higher precedence, so inflating is also a great way to let your users customize their applications. Customization era, no cap π
π§ Simplified application class π§
This is the heart of every full Mojolicious application and it always gets instantiated during server startup. Set it up like:
$ touch lib/MyApp.pm
$ chmod 644 lib/MyApp.pm
We're gonna start by extracting all actions from myapp.pl and turn them into simplified hybrid routes in the Mojolicious::Routes router β none of the actual action code needs to be changed. Iconic.
package MyApp;
use Mojo::Base 'Mojolicious', -signatures;
use MyApp::Model::Users;
sub startup ($self) {
$self->secrets(['Mojolicious rocks']);
$self->helper(users => sub { state $users = MyApp::Model::Users->new });
my $r = $self->routes;
$r->any('/' => sub ($c) {
my $user = $c->param('user') || '';
my $pass = $c->param('pass') || '';
return $c->render unless $c->users->check($user, $pass);
$c->session(user => $user);
$c->flash(message => 'Thanks for logging in.');
$c->redirect_to('protected');
} => 'index');
my $logged_in = $r->under(sub ($c) {
return 1 if $c->session('user');
$c->redirect_to('index');
return undef;
});
$logged_in->get('/protected');
$r->get('/logout' => sub ($c) {
$c->session(expires => 1);
$c->redirect_to('index');
});
}
1;
The startup method gets called right after instantiation and is the place where the whole application gets set up. Since full Mojolicious applications can use nested routes they have no need for group blocks. periodt.
π¦ Simplified application script π¦
So myapp.pl itself can now be turned into a simplified application script to allow running tests again. Slay.
#!/usr/bin/env perl
use Mojo::Base -strict;
use lib qw(lib);
use Mojolicious::Commands;
# Start command line interface for application
Mojolicious::Commands->start_app('MyApp');
And the directory structure of our hybrid application should be looking like this. Look at her go:
myapp
|- myapp.pl
|- lib
| |- MyApp.pm
| +- MyApp
| +- Model
| +- Users.pm
|- t
| +- login.t
+- templates
|- layouts
| +- default.html.ep
|- index.html.ep
+- protected.html.ep
πΈ Controller class πΈ
Hybrid routes are a nice intermediate step, but to maximize maintainability it makes sense to split our action code from its routing information. Main character energy tbh.
$ mkdir lib/MyApp/Controller
$ touch lib/MyApp/Controller/Login.pm
$ chmod 644 lib/MyApp/Controller/Login.pm
Once again the actual action code does not need to change, we just rename $c to $self since the controller is now the invocant. The way that just works? Obsessed.
package MyApp::Controller::Login;
use Mojo::Base 'Mojolicious::Controller', -signatures;
sub index ($self) {
my $user = $self->param('user') || '';
my $pass = $self->param('pass') || '';
return $self->render unless $self->users->check($user, $pass);
$self->session(user => $user);
$self->flash(message => 'Thanks for logging in.');
$self->redirect_to('protected');
}
sub logged_in ($self) {
return 1 if $self->session('user');
$self->redirect_to('index');
return undef;
}
sub logout ($self) {
$self->session(expires => 1);
$self->redirect_to('index');
}
1;
All Mojolicious::Controller controllers are plain old Perl classes and get instantiated on demand. Lowkey beautiful. π«Ά
β¨ Application class β¨
The application class lib/MyApp.pm can now be reduced to model and routing information. Glow-up complete.
package MyApp;
use Mojo::Base 'Mojolicious', -signatures;
use MyApp::Model::Users;
sub startup ($self) {
$self->secrets(['Mojolicious rocks']);
$self->helper(users => sub { state $users = MyApp::Model::Users->new });
my $r = $self->routes;
$r->any('/')->to('login#index')->name('index');
my $logged_in = $r->under('/')->to('login#logged_in');
$logged_in->get('/protected')->to('login#protected');
$r->get('/logout')->to('login#logout');
}
1;
The router allows many different route variations, Mojolicious::Guides::Routing explains them all in great detail. iykyk.
π Templates π
Templates are our views, and usually bound to controllers, so they need to be moved into the appropriate directories. Vibe check: they gotta live where they belong.
$ mkdir templates/login
$ mv templates/index.html.ep templates/login/index.html.ep
$ mv templates/protected.html.ep templates/login/protected.html.ep
π Script π
Finally myapp.pl can be moved into a script directory and renamed to my_app to follow the CPAN standard. We love a clean little script/ moment.
$ mkdir script
$ mv myapp.pl script/my_app
Just a few small details change, instead of a relative path to lib we now use Mojo::File to get an absolute path, allowing us to start the application from outside its home directory. Chef's kiss.
#!/usr/bin/env perl
use strict;
use warnings;
use Mojo::File qw(curfile);
use lib curfile->dirname->sibling('lib')->to_string;
use Mojolicious::Commands;
# Start command line interface for application
Mojolicious::Commands->start_app('MyApp');
π§ͺ Simplified tests π§ͺ
Full Mojolicious applications are a little easier to test, so t/login.t can be simplified. Test era π
use Mojo::Base -strict;
use Test::More;
use Test::Mojo;
my $t = Test::Mojo->new('MyApp');
$t->ua->max_redirects(1);
subtest 'Test login workflow' => sub {
$t->get_ok('/')
->status_is(200)
->element_exists('form input[name="user"]')
->element_exists('form input[name="pass"]')
->element_exists('form input[type="submit"]');
$t->post_ok('/' => form => {user => 'sebastian', pass => 'secr3t'})
->status_is(200)
->text_like('html body' => qr/Welcome sebastian/);
$t->get_ok('/protected')->status_is(200)->text_like('a' => qr/Logout/);
$t->get_ok('/logout')
->status_is(200)
->element_exists('form input[name="user"]')
->element_exists('form input[name="pass"]')
->element_exists('form input[type="submit"]');
};
done_testing();
And our final directory structure should be looking like this. She's fully grown π¦
myapp
|- script
| +- my_app
|- lib
| |- MyApp.pm
| +- MyApp
| |- Controller
| | +- Login.pm
| +- Model
| +- Users.pm
|- t
| +- login.t
+- templates
|- layouts
| +- default.html.ep
+- login
|- index.html.ep
+- protected.html.ep
Test-driven development takes a little getting used to, but can be a very powerful tool. Fr fr, give her a chance.
π MORE π
You can continue with Mojolicious::Guides now or take a look at the Mojolicious wiki (https://github.com/mojolicious/mojo/wiki), which contains a lot more documentation and examples by many different authors. So much lore π
π«Ά SUPPORT π«Ά
If you have any questions the documentation might not yet answer, don't hesitate to ask in the Forum (https://forum.mojolicious.org), or on IRC (https://web.libera.chat/#mojo). The community is iconic, ngl.
okay that's the tea, bestie β this page came from perl v5.42.0, dated 2026-07-15, and it's the Mojolic...Growing(3) manual page. π
β¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-Mojolicious 9.480.0-bp160.2.1 Β· Artistic-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms