/usr/share/perl5/Mojolicious/Guides/Growing.pod is in libmojolicious-perl 5.54+dfsg-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 | =encoding utf8
=head1 NAME
Mojolicious::Guides::Growing - Growing
=head1 OVERVIEW
This document explains the process of starting a L<Mojolicious::Lite>
prototype from scratch and growing it into a well-structured L<Mojolicious>
application.
=head1 CONCEPTS
Essentials every L<Mojolicious> 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 I<controller> is the foundation of pretty much every web framework these
days, including L<Mojolicious>.
+----------------+ +-------+
Request -> | | <-> | Model |
| | +-------+
| Controller |
| | +-------+
Response <- | | <-> | View |
+----------------+ +-------+
The I<controller> receives a request from a user, passes incoming data to the
I<model> and retrieves data from it, which then gets turned into an actual
response by the I<view>. 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<http://mojolicio.us/foo> with your browser, you are basically asking the web
server for the HTML I<representation> of the C<http://mojolicio.us/foo>
I<resource>.
+--------+ +--------+
| | -> http://mojolicio.us/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.
+---------+ +------------+
| | -> PUT /foo -> | |
| | -> Hello world! -> | |
| | | |
| | <- 201 CREATED <- | |
| | | |
| | -> GET /foo -> | |
| Browser | | Web Server |
| | <- 200 OK <- | |
| | <- Hello world! <- | |
| | | |
| | -> DELETE /foo -> | |
| | | |
| | <- 200 OK <- | |
+---------+ +------------+
While HTTP methods such as C<PUT>, C<GET> and C<DELETE> are not directly part
of REST they go very well with it and are commonly used to manipulate
I<resources>.
=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: 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.
Set-Cookie: session=hmac-sha1(base64(json($session)))
In L<Mojolicious> however we are taking this concept one step further by
storing everything JSON serialized and Base64 encoded in HMAC-SHA1 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. Much
of L<Mojolicious> was developed using TDD.
=head1 PROTOTYPE
One of the main differences between L<Mojolicious> and other web frameworks is
that it also includes L<Mojolicious::Lite>, 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<Mojolicious::Lite> applications
don't need more than a single file.
myapp.pl # Templates and even static files can be inlined
Full L<Mojolicious> 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
| +- Controller # Controller 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 with the commands
L<Mojolicious::Command::generate::lite_app> and
L<Mojolicious::Command::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.
=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 $c = shift;
$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
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 A birds-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 L<Mojolicious>, where it will be handled in a few
simple steps.
1. Check if a static file exists that would meet the requirements.
2. Try to find a route that would meet the requirements.
3. Dispatch the request to this route, usually reaching one or more actions.
4. Process the request, maybe generating a response with the renderer.
5. 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!
=head2 Model
In L<Mojolicious> we consider web applications simple frontends for existing
business logic, that means L<Mojolicious> is by design entirely I<model> layer
agnostic and you just use whatever Perl modules you like most.
$ mkdir -p lib/MyApp/Model
$ touch lib/MyApp/Model/Users.pm
$ chmod 644 lib/MyApp/Model/Users.pm
Our login manager will simply use a plain old Perl module abstracting away all
logic related to matching usernames and passwords. The name
C<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;
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<Mojolicious::Lite/"helper"> to make our model available to all actions and
templates.
#!/usr/bin/env perl
use Mojolicious::Lite;
use lib 'lib';
use MyApp::Model::Users;
# Helper to lazy initialize and store our model object
helper users => sub { state $users = MyApp::Model::Users->new };
# /?user=sri&pass=secr3t
any '/' => sub {
my $c = shift;
# 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;
The method L<Mojolicious::Controller/"param"> is used to access query
parameters, C<POST> parameters, file uploads and route placeholders, all at
once.
=head2 Testing
In L<Mojolicious> we take testing very serious and try to make it a pleasant
experience.
$ mkdir t
$ touch t/login.t
$ chmod 644 t/login.t
L<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 L<Mojo::DOM>.
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();
Your application won't pass these tests, but from now on you can use them to
check your progress with the command L<Mojolicious::Command::test>.
$ ./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 with
L<Mojolicious::Command::get>.
$ ./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<Mojolicious> pretty much just work out of the box once you start
using the method L<Mojolicious::Controller/"session">, there is no setup
required, but we suggest setting a more secure passphrase with
L<Mojolicious/"secrets">.
$app->secrets(['Mojolicious rocks']);
This passphrase is used by the HMAC-SHA1 algorithm to make signed cookies
secure and can be changed at any time to invalidate all existing sessions.
$c->session(user => 'sri');
my $user = $c->session('user');
By default all sessions expire after one hour, for more control you can use
the C<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 C<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 C<302> redirect performed with
L<Mojolicious::Controller/"redirect_to">, you can use the flash, accessible
through the method L<Mojolicious::Controller/"flash">.
$c->flash(message => 'Everything is fine.');
$c->redirect_to('goodbye');
Just remember that all session data gets serialized with L<Mojo::JSON> and
stored in HMAC-SHA1 signed cookies, which usually have a C<4096> byte (4KB)
limit, depending on browser.
=head2 Final prototype
A final C<myapp.pl> prototype passing all of the tests above could look like
this.
#!/usr/bin/env perl
use Mojolicious::Lite;
use lib 'lib';
use MyApp::Model::Users;
# Make signed cookies secure
app->secrets(['Mojolicious rocks']);
helper users => sub { state $users = MyApp::Model::Users->new };
# Main login action
any '/' => sub {
my $c = shift;
# 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 {
my $c = shift;
# 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 {
my $c = shift;
# 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,
L<Mojolicious::Guides::Rendering> explains them all in great detail.
=head1 WELL-STRUCTURED APPLICATION
Due to the flexibility of L<Mojolicious> 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<DATA> section can be
automatically turned into separate files in the C<templates> and C<public>
directories with the command L<Mojolicious::Command::inflate>.
$ ./myapp.pl inflate
Those directories have a higher precedence, 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<Mojolicious> 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<myapp.pl> and turn them into
simplified hybrid routes in the L<Mojolicious::Routes> router, none of the
actual action code needs to be changed.
package MyApp;
use Mojo::Base 'Mojolicious';
use MyApp::Model::Users;
sub startup {
my $self = shift;
$self->secrets(['Mojolicious rocks']);
$self->helper(users => sub { state $users = MyApp::Model::Users->new });
my $r = $self->routes;
$r->any('/' => sub {
my $c = shift;
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 {
my $c = shift;
return 1 if $c->session('user');
$c->redirect_to('index');
return undef;
});
$logged_in->get('/protected');
$r->get('/logout' => sub {
my $c = shift;
$c->session(expires => 1);
$c->redirect_to('index');
});
}
1;
The C<startup> method gets called right after instantiation and is the place
where the whole application gets set up. Since full L<Mojolicious>
applications can use nested routes they have no need for C<group> blocks.
=head2 Simplified application script
C<myapp.pl> itself can now be turned into a simplified application script to
allow running 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');
And the directory structure of our hybrid application should be looking like
this.
myapp
|- myapp.pl
|- lib
| |- MyApp.pm
| +- MyApp
| +- Model
| +- Users.pm
|- t
| +- login.t
+- templates
|- layouts
| +- default.html.ep
|- index.html.ep
+- protected.html.ep
=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/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<$c> to C<$self> since the controller is now the invocant.
package MyApp::Controller::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 1 if $self->session('user');
$self->redirect_to('index');
return undef;
}
sub logout {
my $self = shift;
$self->session(expires => 1);
$self->redirect_to('index');
}
1;
All L<Mojolicious::Controller> controllers are plain old Perl classes and get
instantiated on demand.
=head2 Application class
The application class C<lib/MyApp.pm> can now be reduced to model and routing
information.
package MyApp;
use Mojo::Base 'Mojolicious';
use MyApp::Model::Users;
sub startup {
my $self = shift;
$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,
L<Mojolicious::Guides::Routing> explains them all in great detail.
=head2 Templates
Templates are our views, and 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<myapp.pl> can be replaced with a proper L<Mojolicious> 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<lib>
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
Full L<Mojolicious> applications are a little easier to test, so C<t/login.t>
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();
And our final directory structure should be looking like this.
myapp
|- script
| +- myapp
|- 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.
=head1 MORE
You can continue with L<Mojolicious::Guides> now or take a look at the
L<Mojolicious wiki|http://github.com/kraih/mojo/wiki>, 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<mailing-list|http://groups.google.com/group/mojolicious> or the official IRC
channel C<#mojo> on C<irc.perl.org>.
=cut
|