.\" Automatically generated by Pod::Man 2.25 (Pod::Simple 3.16)
.\"
.\" 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
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
'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 turned on, 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.
.ie \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.el \{\
. de IX
..
.\}
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "Mojolicious::Guides::Growing 3pm"
.TH Mojolicious::Guides::Growing 3pm "2012-09-05" "perl v5.14.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
.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.
.SH "CONCEPTS"
.IX Header "CONCEPTS"
Essentials every Mojolicious developer should know.
.SS "Model View Controller"
.IX Subsection "Model View Controller"
\&\s-1MVC\s0 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 \f(CW\*(C`controller\*(C'\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 \f(CW\*(C`controller\*(C'\fR receives a request from a user, passes incoming data to the
\&\f(CW\*(C`model\*(C'\fR and retrieves data from it, which then gets turned into an actual
response by the \f(CW\*(C`view\*(C'\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"
\&\s-1REST\s0 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 \s-1HTTP\s0 these days. In \s-1REST\s0 terms, when you are opening a \s-1URL\s0 like
\&\f(CW\*(C`http://mojolicio.us/foo\*(C'\fR with your browser, you are basically asking the web
server for the \s-1HTML\s0 \f(CW\*(C`representation\*(C'\fR of the \f(CW\*(C`http://mojolicio.us/foo\*(C'\fR
\&\f(CW\*(C`resource\*(C'\fR.
.PP
.Vb 5
\& +\-\-\-\-\-\-\-\-+ +\-\-\-\-\-\-\-\-+
\& | | \-> http://mojolicio.us/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 \s-1HTML\s0, \s-1RSS\s0
or \s-1JSON\s0. 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 \s-1HTTP\s0 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 \s-1REST\s0 they go very well with it and are commonly used to manipulate
\&\f(CW\*(C`resources\*(C'\fR.
.SS "Sessions"
.IX Subsection "Sessions"
\&\s-1HTTP\s0 was designed as a stateless protocol, web servers don't know anything
about previous requests, which makes user-friendly login systems very tricky.
Sessions solve this problem by allowing web applications to keep stateful
information across several \s-1HTTP\s0 requests.
.PP
.Vb 2
\& GET /login?user=sri&pass=s3cret HTTP/1.1
\& Host: mojolicio.us
\&
\& HTTP/1.1 200 OK
\& Set\-Cookie: sessionid=987654321
\& Content\-Length: 10
\& Hello sri.
\&
\& GET /protected HTTP/1.1
\& Host: mojolicio.us
\& Cookie: $Version=1; sessionid=987654321
\&
\& HTTP/1.1 200 OK
\& Set\-Cookie: sessionid=987654321
\& Content\-Length: 16
\& Hello again sri.
.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 2
\& HTTP/1.1 200 OK
\& Set\-Cookie: session=base64(hmac\-md5(json($session)))
.Ve
.PP
In Mojolicious however we are taking this concept one step further by
storing everything in \f(CW\*(C`HMAC\-MD5\*(C'\fR signed cookies, which is more compatible
with the \s-1REST\s0 philosophy and reduces infrastructure requirements.
.SS "Test Driven Development"
.IX Subsection "Test Driven Development"
\&\s-1TDD\s0 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. Most
of Mojolicious was developed using \s-1TDD\s0.
.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 \s-1CPAN\s0 distribution to maximize maintainability.
.PP
.Vb 10
\& myapp # Application directory
\& |\- script # Script directory
\& | +\- myapp # Application script
\& |\- lib # Library directory
\& | |\- MyApp.pm # Application class
\& | +\- MyApp # Application namespace
\& | +\- Example.pm # Controller class
\& |\- 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
.Ve
.PP
Both application skeletons can be automatically generated.
.PP
.Vb 2
\& $ mojo generate lite_app
\& $ mojo generate app
.Ve
.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;
\&
\& get \*(Aq/\*(Aq => sub {
\& my $self = shift;
\& $self\->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
\& Server 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 "Model"
.IX Subsection "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.
.PP
.Vb 3
\& $ mkdir lib
\& $ touch lib/MyUsers.pm
\& $ chmod 644 lib/MyUsers.pm
.Ve
.PP
Our login manager will simply use a plain old Perl module abstracting away all
logic related to matching usernames and passwords.
.PP
.Vb 1
\& package MyUsers;
\&
\& use strict;
\& use warnings;
\&
\& my $USERS = {
\& sri => \*(Aqsecr3t\*(Aq,
\& marcus => \*(Aqlulz\*(Aq,
\& yko => \*(Aqzeecaptain\*(Aq
\& };
\&
\& sub new { bless {}, shift }
\&
\& sub check {
\& my ($self, $user, $pass) = @_;
\&
\& # Success
\& return 1 if $USERS\->{$user} && $USERS\->{$user} eq $pass;
\&
\& # Fail
\& return;
\& }
\&
\& 1;
.Ve
.PP
A simple helper function can be registered with the method
\&\*(L"helper\*(R" in Mojolicious to make our \f(CW\*(C`model\*(C'\fR available to all actions and
templates.
.PP
.Vb 2
\& #!/usr/bin/env perl
\& use Mojolicious::Lite;
\&
\& use lib \*(Aqlib\*(Aq;
\& use MyUsers;
\&
\& # Model object
\& my $users = MyUsers\->new;
\&
\& # Helper function returning our model object
\& helper users => sub { return $users };
\&
\& # /?user=sri&pass=secr3t
\& any \*(Aq/\*(Aq => sub {
\& my $self = shift;
\&
\& # Query parameters
\& my $user = $self\->param(\*(Aquser\*(Aq) || \*(Aq\*(Aq;
\& my $pass = $self\->param(\*(Aqpass\*(Aq) || \*(Aq\*(Aq;
\&
\& # Check password
\& return $self\->render(text => "Welcome $user.")
\& if $self\->users\->check($user, $pass);
\&
\& # Failed
\& $self\->render(text => \*(AqWrong username or password.\*(Aq);
\& };
\&
\& app\->start;
.Ve
.PP
The method \*(L"param\*(R" in Mojolicious::Controller is used to access query
parameters, \s-1POST\s0 parameters, file uploads and route placeholders, all at once.
.SS "Testing"
.IX Subsection "Testing"
In Mojolicious we take test driven development very serious and try to
promote it wherever we can.
.PP
.Vb 3
\& $ mkdir t
\& $ touch t/login.t
\& $ chmod 644 t/login.t
.Ve
.PP
Test::Mojo is a scriptable \s-1HTTP\s0 user agent designed specifically for
testing, with many fun state of the art features such as \s-1CSS3\s0 selectors based
on Mojo::DOM.
.PP
.Vb 2
\& use Test::More tests => 16;
\& use Test::Mojo;
\&
\& # Include application
\& use FindBin;
\& require "$FindBin::Bin/../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(\*(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_form_ok(\*(Aq/\*(Aq => {user => \*(Aqsri\*(Aq, pass => \*(Aqsecr3t\*(Aq})
\& \->status_is(200)\->text_like(\*(Aqhtml body\*(Aq => qr/Welcome sri/);
\&
\& # 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);
.Ve
.PP
From now on you can always check your progress by running these unit tests
against your application.
.PP
.Vb 2
\& $ ./myapp.pl test
\& $ ./myapp.pl test t/login.t
.Ve
.PP
To make the tests less noisy and limit log output to just \f(CW\*(C`error\*(C'\fR messages
you can also add a line like this.
.PP
.Vb 1
\& $t\->app\->log\->level(\*(Aqerror\*(Aq);
.Ve
.PP
Quick \f(CW\*(C`GET\*(C'\fR requests can be performed right from the command line.
.PP
.Vb 2
\& $ ./myapp.pl get /
\& Wrong username or password.
\&
\& $ ./myapp.pl get \-v \*(Aq/?user=sri&pass=secr3t\*(Aq
\& HTTP/1.1 200 OK
\& Connection: Keep\-Alive
\& Date: Sun, 18 Jul 2010 13:09:58 GMT
\& Server: Mojolicious (Perl)
\& Content\-Length: 12
\& Content\-Type: text/plain
\&
\& Welcome sri.
.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 \*(L"session\*(R" in Mojolicious::Controller, there is no setup
required, but we suggest setting a more secure passphrase with
\&\*(L"secret\*(R" in Mojolicious.
.PP
.Vb 1
\& app\->secret(\*(AqMojolicious rocks\*(Aq);
.Ve
.PP
This passphrase is used by the \f(CW\*(C`HMAC\-MD5\*(C'\fR algorithm to make signed cookies
secure and can be changed at any time to invalidate all existing sessions.
.PP
.Vb 2
\& $self\->session(user => \*(Aqsri\*(Aq);
\& my $user = $self\->session(\*(Aquser\*(Aq);
.Ve
.PP
By default all sessions expire after one hour, for more control you can also
use the \f(CW\*(C`expires\*(C'\fR session value to set the expiration date to a specific time
in epoch seconds.
.PP
.Vb 1
\& $self\->session(expires => time + 3600);
.Ve
.PP
And the whole session can be deleted by setting an expiration date in the
past.
.PP
.Vb 1
\& $self\->session(expires => 1);
.Ve
.PP
For data that should only be visible on the next request, like a confirmation
message after a 302 redirect, you can use the flash, accessible through the
method \*(L"flash\*(R" in Mojolicious::Controller.
.PP
.Vb 2
\& $self\->flash(message => \*(AqEverything is fine.\*(Aq);
\& $self\->redirect_to(\*(Aqgoodbye\*(Aq);
.Ve
.PP
Just remember that everything is stored in \f(CW\*(C`HMAC\-MD5\*(C'\fR signed cookies, so
there is usually a 4096 byte limit, depending on the browser.
.SS "Final prototype"
.IX Subsection "Final prototype"
A final \f(CW\*(C`myapp.pl\*(C'\fR prototype passing all of the unit tests above could look
like this.
.PP
.Vb 2
\& #!/usr/bin/env perl
\& use Mojolicious::Lite;
\&
\& use lib \*(Aqlib\*(Aq;
\& use MyUsers;
\&
\& # Make signed cookies secure
\& app\->secret(\*(AqMojolicious rocks\*(Aq);
\&
\& my $users = MyUsers\->new;
\& helper users => sub { return $users };
\&
\& # Main login action
\& any \*(Aq/\*(Aq => sub {
\& my $self = shift;
\&
\& # Query or POST parameters
\& my $user = $self\->param(\*(Aquser\*(Aq) || \*(Aq\*(Aq;
\& my $pass = $self\->param(\*(Aqpass\*(Aq) || \*(Aq\*(Aq;
\&
\& # Check password and render "index.html.ep" if necessary
\& return $self\->render unless $self\->users\->check($user, $pass);
\&
\& # Store username in session
\& $self\->session(user => $user);
\&
\& # Store a friendly message for the next page in flash
\& $self\->flash(message => \*(AqThanks for logging in.\*(Aq);
\&
\& # Redirect to protected page with a 302 response
\& $self\->redirect_to(\*(Aqprotected\*(Aq);
\& } => \*(Aqindex\*(Aq;
\&
\& # A protected page auto rendering "protected.html.ep"
\& get \*(Aq/protected\*(Aq => sub {
\& my $self = shift;
\&
\& # Redirect to main page with a 302 response if user is not logged in
\& return $self\->redirect_to(\*(Aqindex\*(Aq) unless $self\->session(\*(Aquser\*(Aq);
\& };
\&
\& # Logout action
\& get \*(Aq/logout\*(Aq => sub {
\& my $self = shift;
\&
\& # Expire and in turn clear session automatically
\& $self\->session(expires => 1);
\&
\& # Redirect to main page with a 302 response
\& $self\->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 $message = flash \*(Aqmessage\*(Aq) {
\& <%= $message %>
\& % }
\& Welcome <%= session \*(Aquser\*(Aq %>.
\& %= link_to Logout => \*(Aqlogout\*(Aq
\&
\& @@ layouts/default.html.ep
\&
\&
\&