CONTENTS

NAME

Mojolicious - Real-time web framework

SYNOPSIS

# Application
package MyApp;
use Mojo::Base 'Mojolicious', -signatures;

# Route
sub startup ($self) {
  $self->routes->get('/hello')->to('foo#hello');
}

# Controller
package MyApp::Controller::Foo;
use Mojo::Base 'Mojolicious::Controller', -signatures;

# Action
sub hello ($self) {
  $self->render(text => 'Hello World!');
}

DESCRIPTION

An amazing real-time web framework built on top of the powerful Mojo web development toolkit. With support for RESTful routes, plugins, commands, Perl-ish templates, content negotiation, session management, form validation, testing framework, static file server, CGI/PSGI detection, first class Unicode support and much more for you to discover.

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

HOOKS

Mojolicious will emit the following hooks in the listed order.

before_command

Emitted right before the application runs a command through the command line interface.

$app->hook(before_command => sub ($command, $args) {...});

Useful for reconfiguring the application before running a command or to modify the behavior of a command. (Passed the command object and the command arguments)

before_server_start

Emitted right before the application server is started, for web servers that support it, which includes all the built-in ones.

$app->hook(before_server_start => sub ($server, $app) {...});

Useful for reconfiguring application servers dynamically or collecting server diagnostics information. (Passed the server and application objects)

after_build_tx

Emitted right after the transaction is built and before the HTTP request gets parsed.

$app->hook(after_build_tx => sub ($tx, $app) {...});

This is a very powerful hook and should not be used lightly, it makes some rather advanced features such as upload progress bars possible. Note that this hook will not work for embedded applications, because only the host application gets to build transactions. (Passed the transaction and application objects)

around_dispatch

Emitted right after a new request has been received and wraps around the whole dispatch process, so you have to manually forward to the next hook if you want to continue the chain. Default exception handling with "reply->exception" in Mojolicious::Plugin::DefaultHelpers is the first hook in the chain and a call to "dispatch" the last, yours will be in between.

$app->hook(around_dispatch => sub ($next, $c) {
  ...
  $next->();
  ...
});

This is a very powerful hook and should not be used lightly, it allows you to, for example, customize application-wide exception handling, consider it the sledgehammer in your toolbox. (Passed a callback leading to the next hook and the default controller object)

before_dispatch

Emitted right before the static file server and router start their work.

$app->hook(before_dispatch => sub ($c) {...});

Very useful for rewriting incoming requests and other preprocessing tasks. (Passed the default controller object)

after_static

Emitted after a static file response has been generated by the static file server.

$app->hook(after_static => sub ($c) {...});

Mostly used for post-processing static file responses. (Passed the default controller object)

before_routes

Emitted after the static file server determined if a static file should be served and before the router starts its work.

$app->hook(before_routes => sub ($c) {...});

Mostly used for custom dispatchers and collecting metrics. (Passed the default controller object)

around_action

Emitted right before an action gets executed and wraps around it, so you have to manually forward to the next hook if you want to continue the chain. Default action dispatching is the last hook in the chain, yours will run before it.

$app->hook(around_action => sub ($next, $c, $action, $last) {
  ...
  return $next->();
});

This is a very powerful hook and should not be used lightly, it allows you for example to pass additional arguments to actions or handle return values differently. Note that this hook can trigger more than once for the same request if there are nested routes. (Passed a callback leading to the next hook, the current controller object, the action callback and a flag indicating if this action is an endpoint)

before_render

Emitted before content is generated by the renderer. Note that this hook can trigger out of order due to its dynamic nature, and with embedded applications will only work for the application that is rendering.

$app->hook(before_render => sub ($c, $args) {...});

Mostly used for pre-processing arguments passed to the renderer. (Passed the current controller object and the render arguments)

after_render

Emitted after content has been generated by the renderer that will be assigned to the response. Note that this hook can trigger out of order due to its dynamic nature, and with embedded applications will only work for the application that is rendering.

$app->hook(after_render => sub ($c, $output, $format) {...});

Mostly used for post-processing dynamically generated content. (Passed the current controller object, a reference to the content and the format)

after_dispatch

Emitted in reverse order after a response has been generated. Note that this hook can trigger out of order due to its dynamic nature, and with embedded applications will only work for the application that is generating the response.

$app->hook(after_dispatch => sub ($c) {...});

Useful for rewriting outgoing responses and other post-processing tasks. (Passed the current controller object)

ATTRIBUTES

Mojolicious implements the following attributes.

commands

my $commands = $app->commands;
$app         = $app->commands(Mojolicious::Commands->new);

Command line interface for your application, defaults to a Mojolicious::Commands object.

# Add another namespace to load commands from
push @{$app->commands->namespaces}, 'MyApp::Command';

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. Note that this class needs to have already been loaded before the first request arrives.

exception_format

my $format = $app->exception_format;
$app       = $app->exception_format('txt');

Format for HTTP exceptions (html, json, or txt), defaults to html.

home

my $home = $app->home;
$app     = $app->home(Mojo::Home->new);

The home directory of your application, defaults to a Mojo::Home object which stringifies to the actual path.

# Portably generate path relative to home directory
my $path = $app->home->child('data', 'important.txt');

log

my $log = $app->log;
$app    = $app->log(Mojo::Log->new);

The logging layer of your application, defaults to a Mojo::Log object. The level will default to either the MOJO_LOG_LEVEL environment variable, trace if the "mode" is development, or info otherwise. All messages will be written to STDERR by default.

# Log debug message
$app->log->debug('It works');

max_request_size

my $max = $app->max_request_size;
$app    = $app->max_request_size(16777216);

Maximum request size in bytes, defaults to the value of "max_message_size" in Mojo::Message. Setting the value to 0 will allow requests of indefinite size. Note that increasing this value can also drastically increase memory usage, should you for example attempt to parse an excessively large request body with the methods "dom" in Mojo::Message or "json" in Mojo::Message.

mode

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

The operating mode for your application, defaults to a value from the MOJO_MODE and PLACK_ENV environment variables or development.

moniker

my $moniker = $app->moniker;
$app        = $app->moniker('foo_bar');

Moniker of this application, often used as default filename for configuration files and the like, defaults to decamelizing the application class with "decamelize" in Mojo::Util.

plugins

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

The plugin manager, defaults to a Mojolicious::Plugins object. See the "plugin" method below if you want to load a plugin.

# Add another namespace to load plugins from
push @{$app->plugins->namespaces}, 'MyApp::Plugin';

preload_namespaces

my $namespaces = $app->preload_namespaces;
$app           = $app->preload_namespaces(['MyApp::Controller']);

Namespaces to preload classes from during application startup.

renderer

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

Used to render content, defaults to a Mojolicious::Renderer object. For more information about how to generate content see Mojolicious::Guides::Rendering.

# Enable compression
$app->renderer->compress(1);

# Add another "templates" directory
push @{$app->renderer->paths}, '/home/sri/templates';

# Add another "templates" directory with higher precedence
unshift @{$app->renderer->paths}, '/home/sri/themes/blue/templates';

# Add another class with templates in DATA section
push @{$app->renderer->classes}, 'Mojolicious::Plugin::Fun';

routes

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

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

# Add routes
my $r = $app->routes;
$r->get('/foo/bar')->to('test#foo', title => 'Hello Mojo!');
$r->post('/baz')->to('test#baz');

# Add another namespace to load controllers from
push @{$app->routes->namespaces}, 'MyApp::MyController';

secrets

my $secrets = $app->secrets;
$app        = $app->secrets([$bytes]);

Secret passphrases used for signed cookies and the like, defaults to the "moniker" of this application, which is not very secure, so you should change it!!! As long as you are using the insecure default there will be debug messages in the log file reminding you to change your passphrase. Only the first passphrase is used to create new signatures, but all of them for verification. So you can increase security without invalidating all your existing signed cookies by rotating passphrases, just add new ones to the front and remove old ones from the back.

# Rotate passphrases
$app->secrets(['new_passw0rd', 'old_passw0rd', 'very_old_passw0rd']);

sessions

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

Signed cookie based session manager, 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.

# Enable encrypted sessions
$app->sessions->encrypted(1);

# Change name of cookie used for all sessions
$app->sessions->cookie_name('mysession');

# Disable SameSite feature
$app->sessions->samesite(undef);

static

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

For serving static files from your public directories, defaults to a Mojolicious::Static object.

# Serve static files only with a "/static" prefix
$app->static->prefix('/static');

# Add another "public" directory
push @{$app->static->paths}, '/home/sri/public';

# Add another "public" directory with higher precedence
unshift @{$app->static->paths}, '/home/sri/themes/blue/public';

# Add another class with static files in DATA section
push @{$app->static->classes}, 'Mojolicious::Plugin::Fun';

# Remove built-in favicon
delete $app->static->extra->{'favicon.ico'};

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.

# Add custom MIME type
$app->types->type(twt => 'text/tweet');

ua

my $ua = $app->ua;
$app   = $app->ua(Mojo::UserAgent->new);

A full featured HTTP user agent for use in your applications, defaults to a Mojo::UserAgent object.

# Perform blocking request
say $app->ua->get('example.com')->result->body;

validator

my $validator = $app->validator;
$app          = $app->validator(Mojolicious::Validator->new);

Validate values, defaults to a Mojolicious::Validator object.

# Add validation check
$app->validator->add_check(foo => sub ($v, $name, $value) {
  return $value ne 'foo';
});

# Add validation filter
$app->validator->add_filter(quotemeta => sub ($v, $name, $value) {
  return quotemeta $value;
});

METHODS

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

build_controller

my $c = $app->build_controller;
my $c = $app->build_controller(Mojo::Transaction::HTTP->new);
my $c = $app->build_controller(Mojolicious::Controller->new);

Build default controller object with "controller_class".

# Render template from application
my $foo = $app->build_controller->render_to_string(template => 'foo');

build_tx

my $tx = $app->build_tx;

Build Mojo::Transaction::HTTP object and emit "after_build_tx" hook.

config

my $hash = $app->config;
my $foo  = $app->config('foo');
$app     = $app->config({foo => 'bar', baz => 23});
$app     = $app->config(foo => 'bar', baz => 23);

Application configuration.

# Remove value
my $foo = delete $app->config->{foo};

# Assign multiple values at once
$app->config(foo => 'test', bar => 23);

defaults

my $hash = $app->defaults;
my $foo  = $app->defaults('foo');
$app     = $app->defaults({foo => 'bar', baz => 23});
$app     = $app->defaults(foo => 'bar', baz => 23);

Default values for "stash" in Mojolicious::Controller, assigned for every new request.

# Remove value
my $foo = delete $app->defaults->{foo};

# Assign multiple values at once
$app->defaults(foo => 'test', bar => 23);

dispatch

$app->dispatch(Mojolicious::Controller->new);

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

handler

$app->handler(Mojo::Transaction::HTTP->new);
$app->handler(Mojolicious::Controller->new);

Sets up the default controller and emits the "around_dispatch" hook for every request.

helper

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

Add or replace a helper that will be available as a method of the controller object and the application object, as well as a function in ep templates. For a full list of helpers that are available by default see Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers.

# Helper
$app->helper(cache => sub { state $cache = {} });

# Application
$app->cache->{foo} = 'bar';
my $result = $app->cache->{foo};

# Controller
$c->cache->{foo} = 'bar';
my $result = $c->cache->{foo};

# Template
% cache->{foo} = 'bar';
%= cache->{foo}

hook

$app->hook(after_dispatch => sub {...});

Extend Mojolicious with hooks, which allow code to be shared with all requests indiscriminately, for a full list of available hooks see "HOOKS".

# Dispatchers will not run if there's already a response code defined
$app->hook(before_dispatch => sub ($c) {
  $c->render(text => 'Skipped static file server and router!')
    if $c->req->url->path->to_route =~ /do_not_dispatch/;
});

new

my $app = Mojolicious->new;
my $app = Mojolicious->new(moniker => 'foo_bar');
my $app = Mojolicious->new({moniker => 'foo_bar'});

Construct a new Mojolicious application and call "startup". Will automatically detect your home directory. Also sets up the renderer, static file server, a default set of plugins and an "around_dispatch" hook with the default exception handling.

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, for a full list of example plugins included in the Mojolicious distribution see "PLUGINS" in Mojolicious::Plugins.

server

$app->server(Mojo::Server->new);

Emits the "before_server_start" hook.

start

$app->start;
$app->start(@ARGV);

Start the command line interface for your application. For a full list of commands that are available by default see "COMMANDS" in Mojolicious::Commands. Note that the options -h/--help, --home and -m/--mode, which are shared by all commands, will be parsed from @ARGV during compile time.

# Always start daemon
$app->start('daemon', '-l', 'http://*:8080');

startup

$app->startup;

This is your main hook into the application, it will be called at application startup. Meant to be overloaded in a subclass.

sub startup ($self) {...}

warmup

$app->warmup;

Preload classes from "preload_namespaces" for future use.

HELPERS

In addition to the "ATTRIBUTES" and "METHODS" above you can also call helpers on Mojolicious objects. This includes all helpers from Mojolicious::Plugin::DefaultHelpers and Mojolicious::Plugin::TagHelpers. Note that application helpers are always called with a new default controller object, so they can't depend on or change controller state, which includes request, response and stash.

# Call helper
say $app->dumper({foo => 'bar'});

# Longer version
say $app->build_controller->helpers->dumper({foo => 'bar'});

BUNDLED FILES

The Mojolicious distribution includes a few files with different licenses that have been bundled for internal use.

Mojolicious Artwork

Copyright (C) 2010-2024, Sebastian Riedel.

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

highlight.js

Copyright (C) 2006, Ivan Sagalaev.

Licensed under the BSD License, https://github.com/highlightjs/highlight.js/blob/master/LICENSE.

Bootstrap

Copyright 2011-2020 The Bootstrap Authors.
Copyright 2011-2020 Twitter, Inc.

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

Font Awesome

Licensed under the CC-BY License, Version 4.0 https://creativecommons.org/licenses/by/4.0/ and SIL OFL, Version 1.1 https://opensource.org/licenses/OFL-1.1.

CODE NAMES

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

9.0, Waffle (U+1F9C7)

8.0, Supervillain (U+1F9B9)

7.0, Doughnut (U+1F369)

6.0, Clinking Beer Mugs (U+1F37B)

5.0, Tiger Face (U+1F42F)

4.0, Top Hat (U+1F3A9)

3.0, Rainbow (U+1F308)

2.0, Leaf Fluttering In Wind (U+1F343)

1.0, Snowflake (U+2744)

SPONSORS

AUTHORS

Mojolicious is an open source project that relies on the tireless support of its contributors.

Project Founder

Sebastian Riedel, kraih@mojolicious.org

Core Developers

Current voting members of the core team in alphabetical order:

The following members of the core team are currently on hiatus:

Contributors

In alphabetical order:

COPYRIGHT AND LICENSE

Copyright (C) 2008-2024, Sebastian Riedel and others.

This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.

SEE ALSO

https://github.com/mojolicious/mojo, Mojolicious::Guides, https://mojolicious.org.