The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Mojolicious - Duct Tape For The Web!

SYNOPSIS

  # 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 }

DESCRIPTION

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.

Features

  • An amazing MVC web framework supporting a simplified single file mode through Mojolicious::Lite.

      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.

  • Very clean, portable and Object Oriented pure Perl API without any hidden magic and no requirements besides Perl 5.8.7 (although 5.12+ is recommended).

  • Full stack HTTP 1.1 and WebSocket client/server implementation with IPv6, TLS, Bonjour, IDNA, Comet (long polling), chunking and multipart support.

  • Built-in non-blocking I/O web server supporting libev and hot deployment, perfect for embedding.

  • Automatic CGI, FastCGI and PSGI detection.

  • JSON and HTML5/XML parser with CSS3 selector support.

  • Fresh code based upon years of experience developing Catalyst.

Installation

All you need is a oneliner, it takes less than a minute.

  $ sudo sh -c "curl -L cpanmin.us | perl - Mojolicious"

Getting Started

These three lines are a whole web application.

  use Mojolicious::Lite;

  get '/' => {text => 'Hello World!'};

  app->start;

To run this example with the built-in development web server just put the code into a file and start it with morbo.

  $ morbo hello.pl
  Server available at http://127.0.0.1:3000.

  $ curl http://127.0.0.1:3000/
  Hello World!

Duct Tape For The Web

Web development for humans, making hard things possible and everything fun.

  use Mojolicious::Lite;

  # Simple plain text response
  get '/' => sub {
    my $self = shift;
    $self->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
  % use Time::Piece;
  % my $now = localtime;
  <%= link_to clock => begin %>
    The time is <%= $now->hms %>.
  <% end %>

Growing

Single file prototypes can easily grow into well-structured applications. A controller collects several actions together.

  package MyApp::Example;
  use Mojo::Base 'Mojolicious::Controller';

  # Plain text response
  sub hello {
    my $self = shift;
    $self->render_text('Hello World!');
  }

  # Render external template "templates/example/clock.html.ep"
  sub clock { }

  # 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;

While the application class is unique, you can have as many controllers as you like.

  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;

Larger applications benefit from the separation of actions and routes, especially when working in a team.

  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;

Through all of these changes, your action code and templates can stay almost exactly the same.

  % use Time::Piece;
  % my $now = localtime;
  <%= link_to clock => begin %>
    The time is <%= $now->hms %>.
  <% end %>

Mojolicious has been designed from the ground up for a fun and unique workflow.

Want To Know More?

Take a look at our excellent documentation in Mojolicious::Guides!

ARCHITECTURE

Loosely coupled building blocks, use what you like and just ignore the rest.

  .---------------------------------------------------------------.
  |                                                               |
  |                .----------------------------------------------'
  |                | .--------------------------------------------.
  |   Application  | |              Mojolicious::Lite             |
  |                | '--------------------------------------------'
  |                | .--------------------------------------------.
  |                | |                 Mojolicious                |
  '----------------' '--------------------------------------------'
  .---------------------------------------------------------------.
  |                             Mojo                              |
  '---------------------------------------------------------------'
  .-------. .-----------. .--------. .------------. .-------------.
  |  CGI  | |  FastCGI  | |  PSGI  | |  HTTP 1.1  | |  WebSocket  |
  '-------' '-----------' '--------' '------------' '-------------'

ATTRIBUTES

Mojolicious inherits all attributes from Mojo and implements the following new ones.

controller_class

  my $class = $app->controller_class;
  $app      = $app->controller_class('Mojolicious::Controller');

Class to be used for the default controller, defaults to Mojolicious::Controller.

mode

  my $mode = $app->mode;
  $app     = $app->mode('production');

The operating mode for your application, defaults to the value of the MOJO_MODE environment variable or development. You can also add per mode logic to your application by defining methods named ${mode}_mode in the application class, which will be called right before startup.

  sub development_mode {
    my $self = shift;
    ...
  }

  sub production_mode {
    my $self = shift;
    ...
  }

Right before calling startup and mode specific methods, Mojolicious will pick up the current mode, name the log file after it and raise the log level from debug to info if it has a value other than development.

on_process

  my $process = $app->on_process;
  $app        = $app->on_process(sub {...});

Request processing callback, defaults to calling the 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);
  });

plugins

  my $plugins = $app->plugins;
  $app        = $app->plugins(Mojolicious::Plugins->new);

The plugin loader, defaults to a Mojolicious::Plugins object. You can usually leave this alone, see Mojolicious::Plugin if you want to write a plugin or the plugin method below if you want to load a plugin.

renderer

  my $renderer = $app->renderer;
  $app         = $app->renderer(Mojolicious::Renderer->new);

Used in your application to render content, defaults to a Mojolicious::Renderer object. The two main renderer plugins Mojolicious::Plugin::EPRenderer and Mojolicious::Plugin::EPLRenderer contain more information.

routes

  my $routes = $app->routes;
  $app       = $app->routes(Mojolicious::Routes->new);

The routes dispatcher, defaults to a Mojolicious::Routes object. You use this in your startup method to define the url endpoints for your application.

  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');

A secret passphrase used for signed cookies and the like, defaults to the application name which is not very secure, so you should change it!!! As long as you are using the unsecure default there will be debug messages in the log file reminding you to change your passphrase.

sessions

  my $sessions = $app->sessions;
  $app         = $app->sessions(Mojolicious::Sessions->new);

Simple signed cookie based sessions, defaults to a Mojolicious::Sessions object. You can usually leave this alone, see "session" in Mojolicious::Controller for more information about working with session data.

static

  my $static = $app->static;
  $app       = $app->static(Mojolicious::Static->new);

For serving static assets from your public directory, defaults to a Mojolicious::Static object.

types

  my $types = $app->types;
  $app      = $app->types(Mojolicious::Types->new);

Responsible for connecting file extensions with MIME types, defaults to a Mojolicious::Types object.

  $app->types->type(twt => 'text/tweet');

METHODS

Mojolicious inherits all methods from Mojo and implements the following new ones.

new

  my $app = Mojolicious->new;

Construct a new Mojolicious application. Will automatically detect your home directory and set up logging based on your current operating mode. Also sets up the renderer, static dispatcher and a default set of plugins.

defaults

  my $defaults = $app->defaults;
  my $foo      = $app->defaults('foo');
  $app         = $app->defaults({foo => 'bar'});
  $app         = $app->defaults(foo => 'bar');

Default values for the stash, assigned for every new request.

  $app->defaults->{foo} = 'bar';
  my $foo = $app->defaults->{foo};
  delete $app->defaults->{foo};

dispatch

  $app->dispatch($c);

The heart of every Mojolicious application, calls the static and routes dispatchers for every request and passes them a Mojolicious::Controller object.

handler

  $tx = $app->handler($tx);

Sets up the default controller and calls process for every request.

helper

  $app->helper(foo => sub {...});

Add a new helper that will be available as a method of the controller object and the application object, as well as a function in 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 {...});

Extend Mojolicious by adding hooks to named events.

The following events are available and run in the listed order.

after_build_tx

Triggered right after the transaction is built and before the HTTP request gets parsed, the callbacks of this hook run in the order they were added. One use case would be upload progress bars. (Passed the transaction and application instances)

  $app->hook(after_build_tx => sub {
    my ($tx, $app) = @_;
  });
before_dispatch

Triggered right before the static and routes dispatchers start their work, the callbacks of this hook run in the order they were added. Very useful for rewriting incoming requests and other preprocessing tasks. (Passed the default controller instance)

  $app->hook(before_dispatch => sub {
    my $self = shift;
  });
after_static_dispatch

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;
  });
before_render

Triggered right before the renderer turns the stash into a response, the callbacks of this hook run in the order they were added. 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!

after_dispatch

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('some_thing');
  $app->plugin('some_thing', foo => 23);
  $app->plugin('some_thing', {foo => 23});
  $app->plugin('SomeThing');
  $app->plugin('SomeThing', foo => 23);
  $app->plugin('SomeThing', {foo => 23});
  $app->plugin('MyApp::Plugin::SomeThing');
  $app->plugin('MyApp::Plugin::SomeThing', foo => 23);
  $app->plugin('MyApp::Plugin::SomeThing', {foo => 23});

Load a plugin with "register_plugin" in Mojolicious::Plugins.

The following plugins are included in the Mojolicious distribution as examples.

Mojolicious::Plugin::CallbackCondition

Very versatile route condition for arbitrary callbacks.

Mojolicious::Plugin::Charset

Change the application charset.

Mojolicious::Plugin::Config

Perl-ish configuration files.

Mojolicious::Plugin::DefaultHelpers

General purpose helper collection.

Mojolicious::Plugin::EPLRenderer

Renderer for plain embedded Perl templates.

Mojolicious::Plugin::EPRenderer

Renderer for more sophisiticated embedded Perl templates.

Mojolicious::Plugin::HeaderCondition

Route condition for all kinds of headers.

Mojolicious::Plugin::I18N

Internationalization helpers.

Mojolicious::Plugin::JSONConfig

JSON configuration files.

Mojolicious::Plugin::Mount

Mount whole Mojolicious applications.

Mojolicious::Plugin::PODRenderer

Renderer for POD files and documentation browser.

Mojolicious::Plugin::PoweredBy

Add an X-Powered-By header to outgoing responses.

Mojolicious::Plugin::RequestTimer

Log timing information.

Mojolicious::Plugin::TagHelpers

Template specific helper collection.

start

  Mojolicious->start;
  Mojolicious->start('daemon');

Start the Mojolicious::Commands command line interface for your application.

startup

  $app->startup;

This is your main hook into the application, it will be called at application startup.

  sub startup {
    my $self = shift;
  }

HELPERS

In addition to the attributes and methods above you can also call helpers on instances of Mojolicious. This includes all helpers from Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers.

  $app->log->debug($app->dumper({foo => 'bar'}));

SUPPORT

Web

  http://mojolicio.us

IRC

  #mojo on irc.perl.org

Mailing-List

  http://groups.google.com/group/mojolicious

DEVELOPMENT

Repository

  http://github.com/kraih/mojo

BUNDLED FILES

Mojolicious ships with a few popular static files bundled in the public directory.

Mojolicious Artwork

  Copyright (C) 2010-2011, Sebastian Riedel.

Licensed under the CC-SA License, Version 3.0 http://creativecommons.org/licenses/by-sa/3.0.

jQuery

  Version 1.6.2

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

  Copyright 2011, John Resig.

Licensed under the MIT License, http://creativecommons.org/licenses/MIT.

prettify.js

  Version 1-Jun-2011

A Javascript module and CSS file that allows syntax highlighting of source code snippets in an html page.

  Copyright (C) 2006, Google Inc.

Licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.

CODE NAMES

Every major release of Mojolicious has a code name, these are the ones that have been used in the past.

1.4, Smiling Face With Sunglasses (u1F60E)

1.3, Tropical Drink (u1F379)

1.1, Smiling Cat Face With Heart-Shaped Eyes (u1F63B)

1.0, Snowflake (u2744)

0.999930, Hot Beverage (u2615)

0.999927, Comet (u2604)

0.999920, Snowman (u2603)

AUTHOR

Sebastian Riedel, sri@cpan.org.

CREDITS

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

    Magnus Holm

    Maik Fischer

    Marcus Ramberg

    Mark Stosberg

    Matthew Lineen

    Maksym Komar

    Maxim Vuets

    Michael Harris

    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

    Skye Shaw

    Stanis Trendelenburg

    Tatsuhiko Miyagawa

    Terrence Brannon

    The Perl Foundation

    Tomas Znamenacek

    Ulrich Habel

    Ulrich Kautz

    Uwe Voelker

    Viacheslav Tykhanovskyi

    Victor Engmark

    Yaroslav Korshak

    Yuki Kimoto

    Zak B. Elep

COPYRIGHT AND LICENSE

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.