=encoding utf8 =head1 NAME Mojolicious::Guides::Growing - Growing =head1 OVERVIEW This document explains the process of starting a L prototype from scratch and growing it into a well structured L application. =head1 CONCEPTS Essentials every L developer should know. =head2 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. +------------+ +-------+ +------+ Input -> | Controller | -> | Model | -> | View | -> Output +------------+ +-------+ +------+ A slightly modified version of the pattern moving some application logic into the C is the foundation of pretty much every web framework these days, including L. +----------------+ +-------+ Request -> | | <-> | Model | | | +-------+ | Controller | | | +-------+ Response <- | | <-> | View | +----------------+ +-------+ The C receives a request from a user, passes incoming data to the C and retrieves data from it, which then gets turned into an actual response by the C. 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. =head2 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 C with your browser, you are basically asking the web server for the HTML C of the C C. +--------+ +--------+ | | -> http://mojolicio.us/foo -> | | | Client | | Server | | | <- Mojo rocks! <- | | +--------+ +--------+ 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. +---------+ +------------+ | | -> 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 very well with it and are commonly used to manipulate C. =head2 Sessions HTTP 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 HTTP requests. 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. 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. HTTP/1.1 200 OK Set-Cookie: session=hmac-sha1(base64(json($session))) In L however we are taking this concept one step further by storing everything C serialized and C encoded in C signed cookies, which is more compatible with the REST philosophy and reduces infrastructure requirements. =head2 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. Most of L was developed using TDD. =head1 PROTOTYPE One of the main differences between L and other web frameworks is that it also includes L, a micro web framework optimized for rapid prototyping. =head2 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 L applications don't need more than a single file. myapp.pl # Templates and even static files can be inlined Full L applications on the other hand are much closer to a well organized CPAN distribution to maximize maintainability. 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 Both application skeletons can be automatically generated. $ mojo generate lite_app myapp.pl $ mojo generate app MyApp =head2 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; get '/' => sub { my $self = shift; $self->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 Server 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. =head2 Model In L we consider web applications simple frontends for existing business logic, that means L is by design entirely L layer agnostic and you just use whatever Perl modules you like most. $ mkdir lib $ touch lib/MyUsers.pm $ chmod 644 lib/MyUsers.pm Our login manager will simply use a plain old Perl module abstracting away all logic related to matching usernames and passwords. package MyUsers; use strict; use warnings; my $USERS = { sri => 'secr3t', marcus => 'lulz', yko => 'zeecaptain' }; sub new { bless {}, shift } sub check { my ($self, $user, $pass) = @_; # Success return 1 if $USERS->{$user} && $USERS->{$user} eq $pass; # Fail return undef; } 1; A simple helper can be registered with the function L to make our C available to all actions and templates. #!/usr/bin/env perl use Mojolicious::Lite; use lib 'lib'; use MyUsers; # Helper to lazy initialize and store our model object helper users => sub { state $users = MyUsers->new }; # /?user=sri&pass=secr3t any '/' => sub { my $self = shift; # Query parameters my $user = $self->param('user') || ''; my $pass = $self->param('pass') || ''; # Check password return $self->render(text => "Welcome $user.") if $self->users->check($user, $pass); # Failed $self->render(text => 'Wrong username or password.'); }; app->start; The method L is used to access query parameters, POST parameters, file uploads and route placeholders, all at once. =head2 Testing In L we take test driven development very serious and try to promote it wherever we can. $ mkdir t $ touch t/login.t $ chmod 644 t/login.t L is a scriptable HTTP user agent designed specifically for testing, with many fun state of the art features such as CSS selectors based on L. use Test::More; 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('/') ->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 => 'sri', pass => 'secr3t'}) ->status_is(200)->text_like('html body' => qr/Welcome sri/); # 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(); From now on you can always check your progress by running these unit tests against your application. $ ./myapp.pl test $ ./myapp.pl test t/login.t $ ./myapp.pl test -v t/login.t Or perform quick requests right from the command line. $ ./myapp.pl get / Wrong username or password. $ ./myapp.pl get -v '/?user=sri&pass=secr3t' GET /?user=sri&pass=secr3t HTTP/1.1 User-Agent: Mojolicious (Perl) Connection: keep-alive Accept-Encoding: gzip Content-Length: 0 Host: localhost:59472 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. =head2 State keeping Sessions in L pretty much just work out of the box once you start using the method L, there is no setup required, but we suggest setting a more secure passphrase with L. app->secret('Mojolicious rocks'); This passphrase is used by the C algorithm to make signed cookies secure and can be changed at any time to invalidate all existing sessions. $self->session(user => 'sri'); my $user = $self->session('user'); By default all sessions expire after one hour, for more control you can use the C session value to set an expiration date in seconds from now. $self->session(expiration => 3600); And the whole session can be deleted by using the C session value to set an absolute expiration date in the past. $self->session(expires => 1); 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. $self->flash(message => 'Everything is fine.'); $self->redirect_to('goodbye'); Just remember that all session data gets serialized with L and stored in C signed cookies, which usually have a 4096 byte limit, depending on browser. =head2 Final prototype A final C prototype passing all of the unit tests above could look like this. #!/usr/bin/env perl use Mojolicious::Lite; use lib 'lib'; use MyUsers; # Make signed cookies secure app->secret('Mojolicious rocks'); helper users => sub { state $users = MyUsers->new }; # Main login action any '/' => sub { my $self = shift; # Query or POST parameters my $user = $self->param('user') || ''; my $pass = $self->param('pass') || ''; # 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 => 'Thanks for logging in.'); # Redirect to protected page with a 302 response $self->redirect_to('protected'); } => 'index'; # Make sure user is logged in for actions in this group group { under sub { my $self = shift; # Redirect to main page with a 302 response if user is not logged in return $self->session('user') || !$self->redirect_to('index'); }; # A protected page auto rendering "protected.html.ep" get '/protected'; }; # Logout action get '/logout' => 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('index'); }; app->start; __DATA__ @@ index.html.ep % layout 'default'; %= form_for index => begin % if (param 'user') { Wrong name or password, please try again.
% } Name:
%= text_field 'user'
Password:
%= password_field 'pass'
%= submit_button 'Login' % end @@ protected.html.ep % layout 'default'; % if (my $msg = flash 'message') { <%= $msg %>
% } Welcome <%= session 'user' %>.
%= link_to Logout => 'logout' @@ layouts/default.html.ep Login Manager <%= content %> A list of all built-in helpers can be found in L and L. =head1 WELL STRUCTURED APPLICATION Due to the flexibility of L there are many variations of the actual growing process, but this should give you a good overview of the possibilities. =head2 Inflating templates All templates and static files inlined in the C section can be automatically turned into separate files in the C and C directories. $ ./myapp.pl inflate Those directories always get priority, so inflating can also be a great way to allow your users to customize their applications. =head2 Simplified application class This is the heart of every full L application and always gets instantiated during server startup. $ touch lib/MyApp.pm $ chmod 644 lib/MyApp.pm We will start by extracting all actions from C and turn them into simplified hybrid routes in the L router, none of the actual action code needs to be changed. package MyApp; use Mojo::Base 'Mojolicious'; use MyUsers; sub startup { my $self = shift; $self->secret('Mojolicious rocks'); $self->helper(users => sub { state $users = MyUsers->new }); my $r = $self->routes; $r->any('/' => sub { my $self = shift; 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'); } => 'index'); my $logged_in = $r->under(sub { my $self = shift; return $self->session('user') || !$self->redirect_to('index'); }); $logged_in->get('/protected'); $r->get('/logout' => sub { my $self = shift; $self->session(expires => 1); $self->redirect_to('index'); }); } 1; The C method gets called right after instantiation and is the place where the whole application gets set up. Since full L applications can use nested routes they have no need for C blocks. =head2 Simplified application script C itself can now be turned into a simplified application script to allow running unit tests again. #!/usr/bin/env perl use strict; use warnings; use lib 'lib'; use Mojolicious::Commands; # Start command line interface for application Mojolicious::Commands->start_app('MyApp'); =head2 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. $ mkdir lib/MyApp $ touch lib/MyApp/Login.pm $ chmod 644 lib/MyApp/Login.pm Once again the actual action code does not change at all. package MyApp::Login; use Mojo::Base 'Mojolicious::Controller'; sub index { my $self = shift; 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 { my $self = shift; return $self->session('user') || !$self->redirect_to('index'); } sub logout { my $self = shift; $self->session(expires => 1); $self->redirect_to('index'); } 1; All L controllers are plain old Perl classes and get instantiated on demand. =head2 Application class The application class C can now be reduced to model and routing information. package MyApp; use Mojo::Base 'Mojolicious'; use MyUsers; sub startup { my $self = shift; $self->secret('Mojolicious rocks'); $self->helper(users => sub { state $users = MyUsers->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; L allows many route variations, choose whatever you like most. =head2 Templates Templates are usually bound to controllers, so they need to be moved into the appropriate directories. $ mkdir templates/login $ mv templates/index.html.ep templates/login/index.html.ep $ mv templates/protected.html.ep templates/login/protected.html.ep =head2 Script Finally C can be replaced with a proper L script. $ rm myapp.pl $ mkdir script $ touch script/myapp $ chmod 744 script/myapp Only a few small details change, since installable scripts can't use L without breaking updated dual-life modules. #!/usr/bin/env perl use strict; use warnings; use FindBin; BEGIN { unshift @INC, "$FindBin::Bin/../lib" } # Start command line interface for application require Mojolicious::Commands; Mojolicious::Commands->start_app('MyApp'); =head2 Simplified tests Normal L applications are a little easier to test, so C can be simplified. use Test::More; use Test::Mojo; # Load application class my $t = Test::Mojo->new('MyApp'); $t->ua->max_redirects(1); $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 => 'sri', pass => 'secr3t'}) ->status_is(200)->text_like('html body' => qr/Welcome sri/); $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(); Test driven development takes a little getting used to, but is very well worth it! =head1 MORE You can continue with L now or take a look at the L, which contains a lot more documentation and examples by many different authors. =head1 SUPPORT If you have any questions the documentation might not yet answer, don't hesitate to ask on the L or the official IRC channel C<#mojo> on C. =cut