| Mojolicious documentation | Contained in the Mojolicious distribution. |
newdefaultsdispatchhandlerhelperhookpluginstartstartupMojolicious - The Web In A Box!
# Mojolicious application
package MyApp;
use Mojo::Base 'Mojolicious';
sub startup {
my $self = shift;
# Routes
my $r = $self->routes;
# Default route
$r->route('/:controller/:action/:id')->to('foo#welcome');
}
# Mojolicious controller
package MyApp::Foo;
use Mojo::Base 'Mojolicious::Controller';
# Say hello
sub welcome {
my $self = shift;
$self->render_text('Hi there!');
}
# Say goodbye from a template (foo/bye.html.ep)
sub bye { shift->render }
Back in the early days of the web, many people learned Perl because of a wonderful Perl library called CGI. It was simple enough to get started without knowing much about the language and powerful enough to keep you going, learning by doing was much fun. While most of the techniques used are outdated now, the idea behind it is not. Mojolicious is a new attempt at implementing this idea using state of the art technology.
Powerful out of the box with RESTful routes, plugins, Perl-ish templates, session management, signed cookies, testing framework, static file server, I18N, first class unicode support and much more for you to discover.
sudo sh -c "curl -L cpanmin.us | perl - Mojolicious"
use Mojolicious::Lite;
get '/' => sub { shift->render_text('Hello World!') };
app->start;
perl.
% perl hello.pl daemon Server available at http://127.0.0.1:3000.
% curl http://127.0.0.1:3000/ Hello World!
use Mojolicious::Lite;
# Simple plain text response
get '/' => sub { shift->render_text('Hello World!') };
# Route associating the "/time" URL to template in DATA section get '/time' => 'clock';
# RESTful web service sending JSON responses
get '/list/:offset' => sub {
my $self = shift;
$self->render_json({list => [0 .. $self->param('offset')]});
};
# Scrape and return information from remote sites
post '/title' => sub {
my $self = shift;
my $url = $self->param('url') || 'http://mojolicio.us';
$self->render_text(
$self->ua->get($url)->res->dom->html->head->title->text);
};
# WebSocket echo service
websocket '/echo' => sub {
my $self = shift;
$self->on_message(sub {
my ($self, $message) = @_;
$self->send_message("echo: $message");
});
};
app->start; __DATA__
@@ clock.html.ep
% my ($second, $minute, $hour) = (localtime(time))[0, 1, 2];
<%= link_to clock => begin %>
The time is <%= $hour %>:<%= $minute %>:<%= $second %>.
<% end %>
package MyApp::Example; use Mojo::Base 'Mojolicious::Controller';
# Plain text response
sub hello { shift->render_text('Hello World!') }
# Render external template "templates/example/clock.html.ep"
sub clock { shift->render }
# RESTful web service sending JSON responses
sub restful {
my $self = shift;
$self->render_json({list => [0 .. $self->param('offset')]});
}
# Scrape and return information from remote sites
sub title {
my $self = shift;
my $url = $self->param('url') || 'http://mojolicio.us';
$self->render_text(
$self->ua->get($url)->res->dom->html->head->title->text);
}
1;
package MyApp::Realtime; use Mojo::Base 'Mojolicious::Controller';
# WebSocket echo service
sub echo {
my $self = shift;
$self->on_message(sub {
my ($self, $message) = @_;
$self->send_message("echo: $message");
});
}
1;
package MyApp; use Mojo::Base 'Mojolicious';
# Runs once on application startup
sub startup {
my $self = shift;
my $r = $self->routes;
# Create a route at "/example" for the "MyApp::Example" controller
my $example = $r->route('/example')->to('example#');
# Connect these HTTP GET routes to actions in the controller
# (paths are relative to the controller)
$example->get('/')->to('#hello');
$example->get('/time')->to('#clock');
$example->get('/list/:offset')->to('#restful');
# All common HTTP verbs are supported
$example->post('/title')->to('#title');
# ... and much, much more
# (including multiple, auto-discovered controllers)
$r->websocket('/echo')->to('realtime#echo');
}
1;
% my ($second, $minute, $hour) = (localtime(time))[0, 1, 2];
<%= link_to clock => begin %>
The time is <%= $hour %>:<%= $minute %>:<%= $second %>.
<% end %>
.---------------------------------------------------------------. | | | .----------------------------------------------' | | .--------------------------------------------. | Application | | Mojolicious::Lite | | | '--------------------------------------------' | | .--------------------------------------------. | | | Mojolicious | '----------------' '--------------------------------------------' .---------------------------------------------------------------. | Mojo | '---------------------------------------------------------------' .-------. .-----------. .--------. .------------. .-------------. | CGI | | FastCGI | | PSGI | | HTTP 1.1 | | WebSocket | '-------' '-----------' '--------' '------------' '-------------'
controller_class my $class = $app->controller_class;
$app = $app->controller_class('Mojolicious::Controller');
mode my $mode = $app->mode;
$app = $app->mode('production');
MOJO_MODE or
development.
Mojo will name the log file after the current mode and modes other than
development will result in limited log output.
$mode_mode.
sub development_mode {
my $self = shift;
}
sub production_mode {
my $self = shift;
}
on_process my $process = $app->on_process;
$app = $app->on_process(sub {...});
dispatch method.
Generally you will use a plugin or controller instead of this, consider it
the sledgehammer in your toolbox.
$app->on_process(sub {
my ($self, $c) = @_;
$self->dispatch($c);
});
pluginsmy $plugins = $app->plugins; $app = $app->plugins(Mojolicious::Plugins->new);
renderermy $renderer = $app->renderer; $app = $app->renderer(Mojolicious::Renderer->new);
routesmy $routes = $app->routes; $app = $app->routes(Mojolicious::Routes->new);
sub startup {
my $self = shift;
my $r = $self->routes;
$r->route('/:controller/:action')->to('test#welcome');
}
secret my $secret = $app->secret;
$app = $app->secret('passw0rd');
sessionsmy $sessions = $app->sessions; $app = $app->sessions(Mojolicious::Sessions->new);
staticmy $static = $app->static; $app = $app->static(Mojolicious::Static->new);
public directory, by default a
Mojolicious::Static object.
typesmy $types = $app->types; $app = $app->types(Mojolicious::Types->new);
$app->types->type(twitter => 'text/tweet');
newmy $app = Mojolicious->new;
defaults my $defaults = $app->defaults;
my $foo = $app->defaults('foo');
$app = $app->defaults({foo => 'bar'});
$app = $app->defaults(foo => 'bar');
$app->defaults->{foo} = 'bar';
my $foo = $app->defaults->{foo};
delete $app->defaults->{foo};
dispatch$app->dispatch($c);
handler$tx = $app->handler($tx);
helper $app->helper(foo => sub {...});
ep templates.
# Helper
$app->helper(add => sub { $_[1] + $_[2] });
# Controller/Application my $result = $self->add(2, 3);
# Template <%= add 2, 3 %>
hook $app->hook(after_dispatch => sub {...});
Triggered right after the transaction is built and before the HTTP request gets parsed. One use case would be upload progress bars. (Passed the transaction and application instances)
$app->hook(after_build_tx => sub {
my ($tx, $app) = @_;
});
Triggered right before the static and routes dispatchers start their work. Very useful for rewriting incoming requests and other preprocessing tasks. (Passed the default controller instance)
$app->hook(before_dispatch => sub {
my $self = shift;
});
Triggered after the static dispatcher determined if a static file should be served and before the routes dispatcher starts its work, the callbacks of this hook run in reverse order. Mostly used for custom dispatchers and postprocessing static file responses. (Passed the default controller instance)
$app->hook(after_static_dispatch => sub {
my $self = shift;
});
Triggered right before the renderer turns the stash into a response. Very useful for making adjustments to the stash right before rendering. (Passed the current controller instance and argument hash)
$app->hook(before_render => sub {
my ($self, $args) = @_;
});
Note that this hook is EXPERIMENTAL and might change without warning!
Triggered after a response has been rendered, the callbacks of this hook run
in reverse order.
Note that this hook can trigger before after_static_dispatch due to its
dynamic nature.
Useful for all kinds of postprocessing tasks.
(Passed the current controller instance)
$app->hook(after_dispatch => sub {
my $self = shift;
});
plugin $app->plugin('something');
$app->plugin('something', foo => 23);
$app->plugin('something', {foo => 23});
$app->plugin('Foo::Bar');
$app->plugin('Foo::Bar', foo => 23);
$app->plugin('Foo::Bar', {foo => 23});
Very versatile route condition for arbitrary callbacks.
Change the application charset.
Perl-ish configuration files.
General purpose helper collection.
Renderer for plain embedded Perl templates.
Renderer for more sophisiticated embedded Perl templates.
Route condition for all kinds of headers.
Internationalization helpers.
JSON configuration files.
Mount whole Mojolicious applications.
Renderer for POD files and documentation browser.
Add an X-Powered-By header to outgoing responses.
Log timing information.
Template specific helper collection.
start Mojolicious->start;
Mojolicious->start('daemon');
startup$app->startup;
sub startup {
my $self = shift;
}
http://mojolicio.us
#mojo on irc.perl.org
http://groups.google.com/group/mojolicious
http://github.com/kraih/mojo
Copyright (C) 2010-2011, Sebastian Riedel.
Version 1.6.1
Copyright 2011, John Resig.
Version 1-Jun-2011
Copyright (C) 2006, Google Inc.
Smiling Face With Sunglasses (u1F60E)
Tropical Drink (u1F379)
Smiling Cat Face With Heart-Shaped Eyes (u1F63B)
Snowflake (u2744)
Hot Beverage (u2615)
Comet (u2604)
Snowman (u2603)
sri@cpan.org.
Viacheslav Tykhanovskyi, vti@cpan.org.
In alphabetical order.
Abhijit Menon-Sen
Adam Kennedy
Adriano Ferreira
Al Newkirk
Alex Salimon
Alexey Likhatskiy
Anatoly Sharifulin
Andre Vieth
Andrew Fresh
Andreas Koenig
Andy Grundman
Aristotle Pagaltzis
Ashley Dev
Ask Bjoern Hansen
Audrey Tang
Ben van Staveren
Breno G. de Oliveira
Brian Duggan
Burak Gursoy
Ch Lamprecht
Charlie Brady
Chas. J. Owens IV
Christian Hansen
chromatic
Curt Tilmes
Daniel Kimsey
Danijel Tasov
David Davis
Dmitriy Shalashov
Dmitry Konstantinov
Eugene Toropov
Gisle Aas
Glen Hinkle
Graham Barr
Henry Tang
Hideki Yamamura
James Duncan
Jan Jona Javorsek
Jaroslav Muhin
Jesse Vincent
John Kingsley
Jonathan Yu
Kazuhiro Shibuya
Kevin Old
KITAMURA Akatsuki
Lars Balker Rasmussen
Leon Brocard
Maik Fischer
Marcus Ramberg
Mark Stosberg
Matthew Lineen
Maksym Komar
Maxim Vuets
Mirko Westermeier
Mons Anderson
Moritz Lenz
Nils Diewald
Oleg Zhelo
Pascal Gaudette
Paul Tomlin
Pedro Melo
Peter Edwards
Pierre-Yves Ritschard
Quentin Carbonneaux
Rafal Pocztarski
Randal Schwartz
Robert Hicks
Robin Lee
Roland Lammel
Ryan Jendoubi
Sascha Kiefer
Sergey Zasenko
Simon Bertrang
Simone Tampieri
Shu Cho
Stanis Trendelenburg
Tatsuhiko Miyagawa
Terrence Brannon
The Perl Foundation
Tomas Znamenacek
Ulrich Habel
Ulrich Kautz
Uwe Voelker
Victor Engmark
Yaroslav Korshak
Yuki Kimoto
Zak B. Elep
Copyright (C) 2008-2011, Sebastian Riedel.
This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.
| Mojolicious documentation | Contained in the Mojolicious distribution. |
package Mojolicious; use Mojo::Base 'Mojo'; use Carp 'croak'; use Mojolicious::Commands; use Mojolicious::Controller; use Mojolicious::Plugins; use Mojolicious::Renderer; use Mojolicious::Routes; use Mojolicious::Sessions; use Mojolicious::Static; use Mojolicious::Types; has controller_class => 'Mojolicious::Controller'; has mode => sub { ($ENV{MOJO_MODE} || 'development') }; has on_process => sub { sub { shift->dispatch(@_) } }; has plugins => sub { Mojolicious::Plugins->new }; has renderer => sub { Mojolicious::Renderer->new }; has routes => sub { Mojolicious::Routes->new }; has secret => sub { my $self = shift; # Warn developers about unsecure default $self->log->debug('Your secret passphrase needs to be changed!!!'); # Default to application name ref $self; }; has sessions => sub { Mojolicious::Sessions->new }; has static => sub { Mojolicious::Static->new }; has types => sub { Mojolicious::Types->new }; our $CODENAME = 'Smiling Face With Sunglasses'; our $VERSION = '1.48'; # "These old doomsday devices are dangerously unstable. # I'll rest easier not knowing where they are." sub AUTOLOAD { my $self = shift; # Method my ($package, $method) = our $AUTOLOAD =~ /^([\w\:]+)\:\:(\w+)$/; # Check for helper croak qq/Can't locate object method "$method" via package "$package"/ unless my $helper = $self->renderer->helpers->{$method}; # Call helper with fresh controller $self->controller_class->new(app => $self)->$helper(@_); } sub DESTROY { } # "I personalized each of your meals. # For example, Amy: you're cute, so I baked you a pony." sub new { my $self = shift->SUPER::new(@_); # Transaction builder $self->on_transaction( sub { my $self = shift; my $tx = Mojo::Transaction::HTTP->new; $self->plugins->run_hook(after_build_tx => ($tx, $self)); $tx; } ); # Root directories my $home = $self->home; $self->renderer->root($home->rel_dir('templates')); $self->static->root($home->rel_dir('public')); # Default to application namespace my $r = $self->routes; $r->namespace(ref $self); # Hide own controller methods $r->hide(qw/AUTOLOAD DESTROY client cookie delayed finish finished/); $r->hide(qw/flash handler helper on_message param redirect_to render/); $r->hide(qw/render_content render_data render_exception render_json/); $r->hide(qw/render_not_found render_partial render_static render_text/); $r->hide(qw/rendered send_message session signed_cookie url_for/); $r->hide(qw/write write_chunk/); # Prepare log my $mode = $self->mode; $self->log->path($home->rel_file("log/$mode.log")) if -w $home->rel_file('log'); # Load default plugins $self->plugin('callback_condition'); $self->plugin('header_condition'); $self->plugin('default_helpers'); $self->plugin('tag_helpers'); $self->plugin('epl_renderer'); $self->plugin('ep_renderer'); $self->plugin('request_timer'); $self->plugin('powered_by'); # Reduced log output outside of development mode $self->log->level('info') unless $mode eq 'development'; # Run mode $mode = $mode . '_mode'; $self->$mode(@_) if $self->can($mode); # Startup $self->startup(@_); $self; } # "Amy, technology isn't intrinsically good or evil. It's how it's used. # Like the Death Ray." sub defaults { my $self = shift; # Hash $self->{defaults} ||= {}; return $self->{defaults} unless @_; # Get return $self->{defaults}->{$_[0]} unless @_ > 1 || ref $_[0]; # Set my $values = ref $_[0] ? $_[0] : {@_}; for my $key (keys %$values) { $self->{defaults}->{$key} = $values->{$key}; } $self; } # The default dispatchers with exception handling sub dispatch { my ($self, $c) = @_; # Prepare transaction my $tx = $c->tx; $c->res->code(undef) if $tx->is_websocket; $self->sessions->load($c); my $plugins = $self->plugins; $plugins->run_hook(before_dispatch => $c); # Try to find a static file $self->static->dispatch($c); $plugins->run_hook_reverse(after_static_dispatch => $c); # Routes my $res = $tx->res; return if $res->code; if (my $code = ($tx->req->error)[1]) { $res->code($code) } elsif ($tx->is_websocket) { $res->code(426) } unless ($self->routes->dispatch($c)) { $c->render_not_found unless $res->code; } } # "Bite my shiny metal ass!" sub handler { my ($self, $tx) = @_; # Embedded application my $stash = {}; if ($tx->can('stash')) { $stash = $tx->stash; $tx = $tx->tx; } # Build default controller and process my $defaults = $self->defaults; @{$stash}{keys %$defaults} = values %$defaults; my $c = $self->controller_class->new(app => $self, stash => $stash, tx => $tx); unless (eval { $self->on_process->($self, $c); 1 }) { $self->log->fatal("Processing request failed: $@"); $tx->res->code(500); $tx->resume; } # Delayed $self->log->debug('Nothing has been rendered, assuming delayed response.') unless $stash->{'mojo.rendered'} || $tx->is_writing; } # "This snow is beautiful. I'm glad global warming never happened. # Actually, it did. But thank God nuclear winter canceled it out." sub helper { my $self = shift; my $name = shift; my $r = $self->renderer; $self->log->debug(qq/Helper "$name" already exists, replacing./) if exists $r->helpers->{$name}; $r->add_helper($name, @_); } # "He knows when you are sleeping. # He knows when you're on the can. # He'll hunt you down and blast your ass, from here to Pakistan. # Oh... # You better not breathe, you better not move. # You're better off dead, I'm tellin' you, dude. # Santa Claus is gunning you down!" sub hook { shift->plugins->add_hook(@_) } sub plugin { my $self = shift; $self->plugins->register_plugin(shift, $self, @_); } # Start command system sub start { my $class = shift; # Executable $ENV{MOJO_EXE} ||= (caller)[1]; # We are the application $ENV{MOJO_APP} = ref $class ? $class : $class->new; # Start! Mojolicious::Commands->start(@_); } # This will run once at startup sub startup { } 1; __END__