.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Mojolicious::Guides::Growing 3pm" .TH Mojolicious::Guides::Growing 3pm 2024-05-15 "perl v5.38.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME Mojolicious::Guides::Growing \- Growing Mojolicious applications .SH OVERVIEW .IX Header "OVERVIEW" This document explains the process of starting a Mojolicious::Lite prototype from scratch and growing it into a well-structured Mojolicious application. The final result of this guide is also available as an example application . .SH CONCEPTS .IX Header "CONCEPTS" Essentials every Mojolicious developer should know. .SS "Model View Controller" .IX Subsection "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. .PP .Vb 3 \& +\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-+ +\-\-\-\-\-\-+ \& Input \-> | Controller | \-> | Model | \-> | View | \-> Output \& +\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-+ +\-\-\-\-\-\-+ .Ve .PP A slightly modified version of the pattern moving some application logic into the \fIcontroller\fR is the foundation of pretty much every web framework these days, including Mojolicious. .PP .Vb 7 \& +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-+ \& Request \-> | | <\-> | Model | \& | | +\-\-\-\-\-\-\-+ \& | Controller | \& | | +\-\-\-\-\-\-\-+ \& Response <\- | | <\-> | View | \& +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-+ .Ve .PP The \fIcontroller\fR receives a request from a user, passes incoming data to the \fImodel\fR and retrieves data from it, which then gets turned into an actual response by the \fIview\fR. But 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. .SS "REpresentational State Transfer" .IX Subsection "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 \&\f(CW\*(C`http://mojolicious.org/foo\*(C'\fR with your browser, you are basically asking the web server for the HTML \fIrepresentation\fR of the \f(CW\*(C`http://mojolicious.org/foo\*(C'\fR \fIresource\fR. .PP .Vb 5 \& +\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-+ \& | | \-> http://mojolicious.org/foo \-> | | \& | Client | | Server | \& | | <\- Mojo rocks! <\- | | \& +\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-+ .Ve .PP 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. .PP .Vb 10 \& +\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-+ \& | | \-> PUT /foo \-> | | \& | | \-> Hello World! \-> | | \& | | | | \& | | <\- 201 CREATED <\- | | \& | | | | \& | | \-> GET /foo \-> | | \& | Browser | | Web Server | \& | | <\- 200 OK <\- | | \& | | <\- Hello World! <\- | | \& | | | | \& | | \-> DELETE /foo \-> | | \& | | | | \& | | <\- 200 OK <\- | | \& +\-\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-\-\-\-\-+ .Ve .PP While HTTP methods such as \f(CW\*(C`PUT\*(C'\fR, \f(CW\*(C`GET\*(C'\fR and \f(CW\*(C`DELETE\*(C'\fR are not directly part of REST they go well with it and are commonly used to manipulate \fIresources\fR. .SS Sessions .IX Subsection "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. .PP .Vb 2 \& 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. .Ve .PP 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. .PP .Vb 1 \& Set\-Cookie: session=hmac\-sha256(base64(json($session))) .Ve .PP In Mojolicious however we are taking this concept one step further by storing everything JSON serialized and Base64 encoded in HMAC\-SHA256 signed cookies, which is more compatible with the REST philosophy and reduces infrastructure requirements. .SS "Test-Driven Development" .IX Subsection "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. .SH PROTOTYPE .IX Header "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. .SS Differences .IX Subsection "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. .PP .Vb 1 \& myapp.pl # Templates and even static files can be inlined .Ve .PP Full Mojolicious applications on the other hand are much closer to a well organized CPAN distribution to maximize maintainability. .PP .Vb 10 \& 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 .Ve .PP Both application skeletons can be automatically generated with the commands Mojolicious::Command::Author::generate::lite_app and Mojolicious::Command::Author::generate::app. .PP .Vb 2 \& $ mojo generate lite\-app myapp.pl \& $ mojo generate app MyApp .Ve .PP Feature-wise both are almost equal, the only real differences are organizational, so each one can be gradually transformed into the other. .SS Foundation .IX Subsection "Foundation" We start our new application with a single executable Perl script. .PP .Vb 4 \& $ mkdir myapp \& $ cd myapp \& $ touch myapp.pl \& $ chmod 744 myapp.pl .Ve .PP This will be the foundation for our login manager example application. .PP .Vb 2 \& #!/usr/bin/env perl \& use Mojolicious::Lite \-signatures; \& \& get \*(Aq/\*(Aq => sub ($c) { \& $c\->render(text => \*(AqHello World!\*(Aq); \& }; \& \& app\->start; .Ve .PP The built-in development web server makes working on your application a lot of fun thanks to automatic reloading. .PP .Vb 2 \& $ morbo ./myapp.pl \& Web application available at http://127.0.0.1:3000 .Ve .PP Just save your changes and they will be automatically in effect the next time you refresh your browser. .SS "A bird's-eye view" .IX Subsection "A bird's-eye view" It all starts with an HTTP request like this, sent by your browser. .PP .Vb 2 \& GET / HTTP/1.1 \& Host: localhost:3000 .Ve .PP 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. .IP 1. 2 Check if a static file exists that would meet the requirements. .IP 2. 2 Try to find a route that would meet the requirements. .IP 3. 2 Dispatch the request to this route, usually reaching one or more actions. .IP 4. 2 Process the request, maybe generating a response with the renderer. .IP 5. 2 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. .PP 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. .PP .Vb 3 \& HTTP/1.1 200 OK \& Content\-Length: 12 \& Hello World! .Ve .SS Model .IX Subsection "Model" In Mojolicious we consider web applications simple frontends for existing business logic. That means Mojolicious is by design entirely \fImodel\fR layer agnostic, and you just use whatever Perl modules you like most. .PP .Vb 3 \& $ mkdir \-p lib/MyApp/Model \& $ touch lib/MyApp/Model/Users.pm \& $ chmod 644 lib/MyApp/Model/Users.pm .Ve .PP Our login manager will use a plain old Perl module abstracting away all logic related to matching usernames and passwords. The name \f(CW\*(C`MyApp::Model::Users\*(C'\fR is an arbitrary choice, and is simply used to make the separation of concerns more visible. .PP .Vb 1 \& package MyApp::Model::Users; \& \& use strict; \& use warnings; \& use experimental qw(signatures); \& \& use Mojo::Util qw(secure_compare); \& \& my $USERS = { \& joel => \*(Aqlas3rs\*(Aq, \& marcus => \*(Aqlulz\*(Aq, \& sebastian => \*(Aqsecr3t\*(Aq \& }; \& \& 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; .Ve .PP A simple helper can be registered with the function "helper" in Mojolicious::Lite to make our model available to all actions and templates. .PP .Vb 2 \& #!/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 \*(Aq/\*(Aq => sub ($c) { \& \& # Query parameters \& my $user = $c\->param(\*(Aquser\*(Aq) || \*(Aq\*(Aq; \& my $pass = $c\->param(\*(Aqpass\*(Aq) || \*(Aq\*(Aq; \& \& # Check password \& return $c\->render(text => "Welcome $user.") if $c\->users\->check($user, $pass); \& \& # Failed \& $c\->render(text => \*(AqWrong username or password.\*(Aq); \& }; \& \& app\->start; .Ve .PP The method "param" in Mojolicious::Controller is used to access query parameters, \f(CW\*(C`POST\*(C'\fR parameters, file uploads and route placeholders, all at once. .SS Testing .IX Subsection "Testing" In Mojolicious we take testing very seriously and try to make it a pleasant experience. .PP .Vb 3 \& $ mkdir t \& $ touch t/login.t \& $ chmod 644 t/login.t .Ve .PP Test::Mojo is a scriptable HTTP user agent designed specifically for testing, with many fun state-of-the-art features such as CSS selectors based on Mojo::DOM. .PP .Vb 2 \& use Test::More; \& use Test::Mojo; \& \& # Include application \& use Mojo::File qw(curfile); \& require(curfile\->dirname\->sibling(\*(Aqmyapp.pl\*(Aq)); \& \& # Allow 302 redirect responses \& my $t = Test::Mojo\->new; \& $t\->ua\->max_redirects(1); \& \& # Test if the HTML login form exists \& $t\->get_ok(\*(Aq/\*(Aq) \& \->status_is(200) \& \->element_exists(\*(Aqform input[name="user"]\*(Aq) \& \->element_exists(\*(Aqform input[name="pass"]\*(Aq) \& \->element_exists(\*(Aqform input[type="submit"]\*(Aq); \& \& # Test login with valid credentials \& $t\->post_ok(\*(Aq/\*(Aq => form => {user => \*(Aqsebastian\*(Aq, pass => \*(Aqsecr3t\*(Aq}) \& \->status_is(200) \& \->text_like(\*(Aqhtml body\*(Aq => qr/Welcome sebastian/); \& \& # Test accessing a protected page \& $t\->get_ok(\*(Aq/protected\*(Aq)\->status_is(200)\->text_like(\*(Aqa\*(Aq => qr/Logout/); \& \& # Test if HTML login form shows up again after logout \& $t\->get_ok(\*(Aq/logout\*(Aq) \& \->status_is(200) \& \->element_exists(\*(Aqform input[name="user"]\*(Aq) \& \->element_exists(\*(Aqform input[name="pass"]\*(Aq) \& \->element_exists(\*(Aqform input[type="submit"]\*(Aq); \& \& done_testing(); .Ve .PP Your application won't pass these tests, but from now on you can use them to check your progress. .PP .Vb 3 \& $ prove \-l \& $ prove \-l t/login.t \& $ prove \-l \-v t/login.t .Ve .PP Or perform quick requests right from the command line with Mojolicious::Command::get. .PP .Vb 2 \& $ ./myapp.pl get / \& Wrong username or password. \& \& $ ./myapp.pl get \-v \*(Aq/?user=sebastian&pass=secr3t\*(Aq \& 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. .Ve .SS "State keeping" .IX Subsection "State keeping" Sessions in Mojolicious pretty much just work out of the box once you start using the method "session" in Mojolicious::Controller, there is no setup required, but we suggest setting a more secure passphrase with "secrets" in Mojolicious. .PP .Vb 1 \& app\->secrets([\*(AqMojolicious rocks\*(Aq]); .Ve .PP 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. .PP .Vb 2 \& $c\->session(user => \*(Aqsebastian\*(Aq); \& my $user = $c\->session(\*(Aquser\*(Aq); .Ve .PP By default all sessions expire after one hour, for more control you can use the \f(CW\*(C`expiration\*(C'\fR session value to set an expiration date in seconds from now. .PP .Vb 1 \& $c\->session(expiration => 3600); .Ve .PP And the whole session can be deleted by using the \f(CW\*(C`expires\*(C'\fR session value to set an absolute expiration date in the past. .PP .Vb 1 \& $c\->session(expires => 1); .Ve .PP For data that should only be visible on the next request, like a confirmation message after a \f(CW302\fR redirect performed with "redirect_to" in Mojolicious::Plugin::DefaultHelpers, you can use the flash, accessible through "flash" in Mojolicious::Plugin::DefaultHelpers. .PP .Vb 2 \& $c\->flash(message => \*(AqEverything is fine.\*(Aq); \& $c\->redirect_to(\*(Aqgoodbye\*(Aq); .Ve .PP Just remember that all session data gets serialized with Mojo::JSON and stored in HMAC\-SHA256 signed cookies, which usually have a \f(CW4096\fR byte (4KiB) limit, depending on browser. .SS "Final prototype" .IX Subsection "Final prototype" A final \f(CW\*(C`myapp.pl\*(C'\fR prototype passing all of the tests above could look like this. .PP .Vb 2 \& #!/usr/bin/env perl \& use Mojolicious::Lite \-signatures; \& \& use lib qw(lib); \& use MyApp::Model::Users; \& \& # Make signed cookies tamper resistant \& app\->secrets([\*(AqMojolicious rocks\*(Aq]); \& \& helper users => sub { state $users = MyApp::Model::Users\->new }; \& \& # Main login action \& any \*(Aq/\*(Aq => sub ($c) { \& \& # Query or POST parameters \& my $user = $c\->param(\*(Aquser\*(Aq) || \*(Aq\*(Aq; \& my $pass = $c\->param(\*(Aqpass\*(Aq) || \*(Aq\*(Aq; \& \& # 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 => \*(AqThanks for logging in.\*(Aq); \& \& # Redirect to protected page with a 302 response \& $c\->redirect_to(\*(Aqprotected\*(Aq); \& } => \*(Aqindex\*(Aq; \& \& # 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(\*(Aquser\*(Aq); \& $c\->redirect_to(\*(Aqindex\*(Aq); \& return undef; \& }; \& \& # A protected page auto rendering "protected.html.ep" \& get \*(Aq/protected\*(Aq; \& }; \& \& # Logout action \& get \*(Aq/logout\*(Aq => sub ($c) { \& \& # Expire and in turn clear session automatically \& $c\->session(expires => 1); \& \& # Redirect to main page with a 302 response \& $c\->redirect_to(\*(Aqindex\*(Aq); \& }; \& \& app\->start; \& _\|_DATA_\|_ \& \& @@ index.html.ep \& % layout \*(Aqdefault\*(Aq; \& %= form_for index => begin \& % if (param \*(Aquser\*(Aq) { \& Wrong name or password, please try again.
\& % } \& Name:
\& %= text_field \*(Aquser\*(Aq \&
Password:
\& %= password_field \*(Aqpass\*(Aq \&
\& %= submit_button \*(AqLogin\*(Aq \& % end \& \& @@ protected.html.ep \& % layout \*(Aqdefault\*(Aq; \& % if (my $msg = flash \*(Aqmessage\*(Aq) { \& <%= $msg %>
\& % } \& Welcome <%= session \*(Aquser\*(Aq %>.
\& %= link_to Logout => \*(Aqlogout\*(Aq \& \& @@ layouts/default.html.ep \& \& \& Login Manager \& <%= content %> \& .Ve .PP And the directory structure should be looking like this now. .PP .Vb 8 \& myapp \& |\- myapp.pl \& |\- lib \& | +\- MyApp \& | +\- Model \& | +\- Users.pm \& +\- t \& +\- login.t .Ve .PP Our templates are using quite a few features of the renderer, Mojolicious::Guides::Rendering explains them all in great detail. .SH "WELL-STRUCTURED APPLICATION" .IX Header "WELL-STRUCTURED APPLICATION" Due to the flexibility of Mojolicious there are many variations of the actual growing process, but this should give you a good overview of the possibilities. .SS "Inflating templates" .IX Subsection "Inflating templates" All templates and static files inlined in the \f(CW\*(C`DATA\*(C'\fR section can be automatically turned into separate files in the \&\f(CW\*(C`templates\*(C'\fR and \f(CW\*(C`public\*(C'\fR directories with the command Mojolicious::Command::Author::inflate. .PP .Vb 1 \& $ ./myapp.pl inflate .Ve .PP Those directories have a higher precedence, so inflating can also be a great way to allow your users to customize their applications. .SS "Simplified application class" .IX Subsection "Simplified application class" This is the heart of every full Mojolicious application and always gets instantiated during server startup. .PP .Vb 2 \& $ touch lib/MyApp.pm \& $ chmod 644 lib/MyApp.pm .Ve .PP We will start by extracting all actions from \f(CW\*(C`myapp.pl\*(C'\fR and turn them into simplified hybrid routes in the Mojolicious::Routes router, none of the actual action code needs to be changed. .PP .Vb 2 \& package MyApp; \& use Mojo::Base \*(AqMojolicious\*(Aq, \-signatures; \& \& use MyApp::Model::Users; \& \& sub startup ($self) { \& \& $self\->secrets([\*(AqMojolicious rocks\*(Aq]); \& $self\->helper(users => sub { state $users = MyApp::Model::Users\->new }); \& \& my $r = $self\->routes; \& \& $r\->any(\*(Aq/\*(Aq => sub ($c) { \& \& my $user = $c\->param(\*(Aquser\*(Aq) || \*(Aq\*(Aq; \& my $pass = $c\->param(\*(Aqpass\*(Aq) || \*(Aq\*(Aq; \& return $c\->render unless $c\->users\->check($user, $pass); \& \& $c\->session(user => $user); \& $c\->flash(message => \*(AqThanks for logging in.\*(Aq); \& $c\->redirect_to(\*(Aqprotected\*(Aq); \& } => \*(Aqindex\*(Aq); \& \& my $logged_in = $r\->under(sub ($c) { \& return 1 if $c\->session(\*(Aquser\*(Aq); \& $c\->redirect_to(\*(Aqindex\*(Aq); \& return undef; \& }); \& $logged_in\->get(\*(Aq/protected\*(Aq); \& \& $r\->get(\*(Aq/logout\*(Aq => sub ($c) { \& $c\->session(expires => 1); \& $c\->redirect_to(\*(Aqindex\*(Aq); \& }); \& } \& \& 1; .Ve .PP The \f(CW\*(C`startup\*(C'\fR 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 \f(CW\*(C`group\*(C'\fR blocks. .SS "Simplified application script" .IX Subsection "Simplified application script" \&\f(CW\*(C`myapp.pl\*(C'\fR itself can now be turned into a simplified application script to allow running tests again. .PP .Vb 1 \& #!/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(\*(AqMyApp\*(Aq); .Ve .PP And the directory structure of our hybrid application should be looking like this. .PP .Vb 10 \& myapp \& |\- myapp.pl \& |\- lib \& | |\- MyApp.pm \& | +\- MyApp \& | +\- Model \& | +\- Users.pm \& |\- t \& | +\- login.t \& +\- templates \& |\- layouts \& | +\- default.html.ep \& |\- index.html.ep \& +\- protected.html.ep .Ve .SS "Controller class" .IX Subsection "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. .PP .Vb 3 \& $ mkdir lib/MyApp/Controller \& $ touch lib/MyApp/Controller/Login.pm \& $ chmod 644 lib/MyApp/Controller/Login.pm .Ve .PP Once again the actual action code does not need to change, we just rename \f(CW$c\fR to \f(CW$self\fR since the controller is now the invocant. .PP .Vb 2 \& package MyApp::Controller::Login; \& use Mojo::Base \*(AqMojolicious::Controller\*(Aq, \-signatures; \& \& sub index ($self) { \& my $user = $self\->param(\*(Aquser\*(Aq) || \*(Aq\*(Aq; \& my $pass = $self\->param(\*(Aqpass\*(Aq) || \*(Aq\*(Aq; \& return $self\->render unless $self\->users\->check($user, $pass); \& \& $self\->session(user => $user); \& $self\->flash(message => \*(AqThanks for logging in.\*(Aq); \& $self\->redirect_to(\*(Aqprotected\*(Aq); \& } \& \& sub logged_in ($self) { \& return 1 if $self\->session(\*(Aquser\*(Aq); \& $self\->redirect_to(\*(Aqindex\*(Aq); \& return undef; \& } \& \& sub logout ($self) { \& $self\->session(expires => 1); \& $self\->redirect_to(\*(Aqindex\*(Aq); \& } \& \& 1; .Ve .PP All Mojolicious::Controller controllers are plain old Perl classes and get instantiated on demand. .SS "Application class" .IX Subsection "Application class" The application class \f(CW\*(C`lib/MyApp.pm\*(C'\fR can now be reduced to model and routing information. .PP .Vb 2 \& package MyApp; \& use Mojo::Base \*(AqMojolicious\*(Aq, \-signatures; \& \& use MyApp::Model::Users; \& \& sub startup ($self) { \& \& $self\->secrets([\*(AqMojolicious rocks\*(Aq]); \& $self\->helper(users => sub { state $users = MyApp::Model::Users\->new }); \& \& my $r = $self\->routes; \& $r\->any(\*(Aq/\*(Aq)\->to(\*(Aqlogin#index\*(Aq)\->name(\*(Aqindex\*(Aq); \& \& my $logged_in = $r\->under(\*(Aq/\*(Aq)\->to(\*(Aqlogin#logged_in\*(Aq); \& $logged_in\->get(\*(Aq/protected\*(Aq)\->to(\*(Aqlogin#protected\*(Aq); \& \& $r\->get(\*(Aq/logout\*(Aq)\->to(\*(Aqlogin#logout\*(Aq); \& } \& \& 1; .Ve .PP The router allows many different route variations, Mojolicious::Guides::Routing explains them all in great detail. .SS Templates .IX Subsection "Templates" Templates are our views, and usually bound to controllers, so they need to be moved into the appropriate directories. .PP .Vb 3 \& $ mkdir templates/login \& $ mv templates/index.html.ep templates/login/index.html.ep \& $ mv templates/protected.html.ep templates/login/protected.html.ep .Ve .SS Script .IX Subsection "Script" Finally \f(CW\*(C`myapp.pl\*(C'\fR can be moved into a \f(CW\*(C`script\*(C'\fR directory and renamed to \f(CW\*(C`my_app\*(C'\fR to follow the CPAN standard. .PP .Vb 2 \& $ mkdir script \& $ mv myapp.pl script/my_app .Ve .PP 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. .PP .Vb 1 \& #!/usr/bin/env perl \& \& use strict; \& use warnings; \& \& use Mojo::File qw(curfile); \& use lib curfile\->dirname\->sibling(\*(Aqlib\*(Aq)\->to_string; \& use Mojolicious::Commands; \& \& # Start command line interface for application \& Mojolicious::Commands\->start_app(\*(AqMyApp\*(Aq); .Ve .SS "Simplified tests" .IX Subsection "Simplified tests" Full Mojolicious applications are a little easier to test, so \f(CW\*(C`t/login.t\*(C'\fR can be simplified. .PP .Vb 1 \& use Mojo::Base \-strict; \& \& use Test::More; \& use Test::Mojo; \& \& my $t = Test::Mojo\->new(\*(AqMyApp\*(Aq); \& $t\->ua\->max_redirects(1); \& \& subtest \*(AqTest login workflow\*(Aq => sub { \& $t\->get_ok(\*(Aq/\*(Aq) \& \->status_is(200) \& \->element_exists(\*(Aqform input[name="user"]\*(Aq) \& \->element_exists(\*(Aqform input[name="pass"]\*(Aq) \& \->element_exists(\*(Aqform input[type="submit"]\*(Aq); \& \& $t\->post_ok(\*(Aq/\*(Aq => form => {user => \*(Aqsebastian\*(Aq, pass => \*(Aqsecr3t\*(Aq}) \& \->status_is(200) \& \->text_like(\*(Aqhtml body\*(Aq => qr/Welcome sebastian/); \& \& $t\->get_ok(\*(Aq/protected\*(Aq)\->status_is(200)\->text_like(\*(Aqa\*(Aq => qr/Logout/); \& \& $t\->get_ok(\*(Aq/logout\*(Aq) \& \->status_is(200) \& \->element_exists(\*(Aqform input[name="user"]\*(Aq) \& \->element_exists(\*(Aqform input[name="pass"]\*(Aq) \& \->element_exists(\*(Aqform input[type="submit"]\*(Aq); \& }; \& \& done_testing(); .Ve .PP And our final directory structure should be looking like this. .PP .Vb 10 \& 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 .Ve .PP Test-driven development takes a little getting used to, but can be a very powerful tool. .SH MORE .IX Header "MORE" You can continue with Mojolicious::Guides now or take a look at the Mojolicious wiki , which contains a lot more documentation and examples by many different authors. .SH SUPPORT .IX Header "SUPPORT" If you have any questions the documentation might not yet answer, don't hesitate to ask in the Forum , on IRC , or Matrix .