NAME

Mojolicious::Guides::Routing - Routing

OVERVIEW

This document contains a simple and fun introduction to the Mojolicious router and its underlying concepts.

CONCEPTS

Essentials every Mojolicious developer should know.

Dispatcher

The foundation of every web framework is a tiny black box connecting incoming requests with code generating the appropriate response.

  GET /user/show/1 -> $self->render(text => 'Sebastian');

This black box is usually called a dispatcher. There are many implementations using different strategies to establish these connections, but pretty much all are based around mapping the requests path to some kind of response generator.

  /user/show/1 -> $self->render(text => 'Sebastian');
  /user/show/2 -> $self->render(text => 'Sara');
  /user/show/3 -> $self->render(text => 'Baerbel');
  /user/show/4 -> $self->render(text => 'Wolfgang');

While it is very well possible to make all these connections static, it is also rather inefficient. That's why regular expressions are commonly used to make the dispatch process more dynamic.

  qr!/user/show/(\d+)! -> $self->render(text => $users{$1});

Modern dispatchers have pretty much everything HTTP has to offer at their disposal and can use many more variables than just the request path, such as request method and headers like Host, User-Agent and Accept.

  GET /user/show/23 HTTP/1.1
  Host: mojolicio.us
  User-Agent: Mozilla/5.0 (compatible; Mojolicious; Perl)
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Routes

While regular expressions are quite powerful they also tend to be unpleasant to look at and are generally overkill for ordinary path matching.

  qr!/user/show/(\d+)! -> $self->render(text => $users{$1});

This is where routes come into play, they have been designed from the ground up to represent paths with placeholders.

  /user/show/:id -> $self->render(text => $users{$id});

The only difference between a static path and the route above is the :id placeholder. One or more placeholders can be anywhere in the route.

  /user/:action/:id

A fundamental concept of the Mojolicious router is that extracted placeholder values are turned into a hash.

  /user/show/23 -> /user/:action/:id -> {action => 'show', id => 23}

This hash is basically the center of every Mojolicious application, you will learn more about this later on. Internally routes get compiled to regular expressions, so you can get the best of both worlds with a little bit of experience.

  /user/show/:id -> qr/(?-xism:^\/user\/show/([^\/\.]+))/

A trailing slash in the path is always optional.

  /user/show/23/ -> /user/:action/:id -> {action => 'show', id => 23}

Reversibility

One more huge advantage routes have over regular expressions is that they are easily reversible, extracted placeholders can be turned back into a path at any time.

  /sebastian -> /:name -> {name => 'sebastian'}
  {name => 'sebastian'} -> /:name -> /sebastian

Every placeholder has a name, even if it's just an empty string.

Generic placeholders

Generic placeholders are the simplest form of placeholders, they use a colon prefix and match all characters except / and ..

  /hello              -> /:name/hello -> undef
  /sebastian/23/hello -> /:name/hello -> undef
  /sebastian.23/hello -> /:name/hello -> undef
  /sebastian/hello    -> /:name/hello -> {name => 'sebastian'}
  /sebastian23/hello  -> /:name/hello -> {name => 'sebastian23'}
  /sebastian 23/hello -> /:name/hello -> {name => 'sebastian 23'}

All placeholders can be surrounded by parentheses to separate them from the surrounding text.

  /hello             -> /(:name)hello -> undef
  /sebastian/23hello -> /(:name)hello -> undef
  /sebastian.23hello -> /(:name)hello -> undef
  /sebastianhello    -> /(:name)hello -> {name => 'sebastian'}
  /sebastian23hello  -> /(:name)hello -> {name => 'sebastian23'}
  /sebastian 23hello -> /(:name)hello -> {name => 'sebastian 23'}

The colon prefix is optional for generic placeholders that are surrounded by parentheses.

  /i♥mojolicious -> /(one)♥(two) -> {one => 'i', two => 'mojolicious'}

Relaxed placeholders

Relaxed placeholders are just like generic placeholders, but use a hash prefix and match all characters except /.

  /hello              -> /#name/hello -> undef
  /sebastian/23/hello -> /#name/hello -> undef
  /sebastian.23/hello -> /#name/hello -> {name => 'sebastian.23'}
  /sebastian/hello    -> /#name/hello -> {name => 'sebastian'}
  /sebastian23/hello  -> /#name/hello -> {name => 'sebastian23'}
  /sebastian 23/hello -> /#name/hello -> {name => 'sebastian 23'}

Wildcard placeholders

Wildcard placeholders are just like the two placeholders above, but use an asterisk prefix and match absolutely everything, including / and ..

  /hello              -> /*name/hello -> undef
  /sebastian/23/hello -> /*name/hello -> {name => 'sebastian/23'}
  /sebastian.23/hello -> /*name/hello -> {name => 'sebastian.23'}
  /sebastian/hello    -> /*name/hello -> {name => 'sebastian'}
  /sebastian23/hello  -> /*name/hello -> {name => 'sebastian23'}
  /sebastian 23/hello -> /*name/hello -> {name => 'sebastian 23'}

BASICS

Most commonly used features every Mojolicious developer should know about.

Minimal route

The attribute "routes" in Mojolicious contains a router you can use to generate route structures, they match in the same order in which they were defined.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Router
    my $r = $self->routes;

    # Route
    $r->route('/welcome')->to(controller => 'foo', action => 'welcome');
  }

  1;

The minimal route above will load and instantiate the class MyApp::Foo and call its welcome method.

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

  # Action
  sub welcome {
    my $self = shift;

    # Render response
    $self->render(text => 'Hello there.');
  }

  1;

Routes are usually configured in the startup method of the application class, but the router can be accessed from everywhere (even at runtime).

Routing destination

After you start a new route with the method "route" in Mojolicious::Routes, you can also give it a destination in the form of a hash using the chained method "to" in Mojolicious::Routes::Route.

  # /welcome -> {controller => 'foo', action => 'welcome'}
  $r->route('/welcome')->to(controller => 'foo', action => 'welcome');

Now if the route matches an incoming request it will use the content of this hash to try and find appropriate code to generate a response.

Stash

The generated hash of a matching route is actually the center of the whole Mojolicious request cycle. We call it the stash, and it persists until a response has been generated.

  # /bye -> {controller => 'foo', action => 'bye', mymessage => 'Bye'}
  $r->route('/bye')
    ->to(controller => 'foo', action => 'bye', mymessage => 'Bye');

There are a few stash values with special meaning, such as controller and action, but you can generally fill it with whatever data you need to generate a response. Once dispatched the whole stash content can be changed at any time.

  sub bye {
    my $self = shift;

    # Get message from stash
    my $msg = $self->stash('mymessage');

    # Change message in stash
    $self->stash(mymessage => 'Welcome');
  }

For a full list of reserved stash values see "stash" in Mojolicious::Controller.

Nested routes

It is also possible to build tree structures from routes to remove repetitive code. A route with children can't match on its own though, only the actual endpoints of these nested routes can.

  # /foo     -> undef
  # /foo/bar -> {controller => 'foo', action => 'bar'}
  my $foo = $r->route('/foo')->to(controller => 'foo');
  $foo->route('/bar')->to(action => 'bar');

The stash is simply inherited from route to route and newer values override old ones.

  # /foo     -> undef
  # /foo/abc -> undef
  # /foo/bar -> {controller => 'foo', action => 'bar'}
  # /foo/baz -> {controller => 'foo', action => 'baz'}
  # /foo/cde -> {controller => 'foo', action => 'abc'}
  my $foo = $r->route('/foo')->to(controller => 'foo', action => 'abc');
  $foo->route('/bar')->to(action => 'bar');
  $foo->route('/baz')->to(action => 'baz');
  $foo->route('/cde');

Special stash values

When the dispatcher sees controller and action values in the stash it will always try to turn them into a class and method to dispatch to. The controller value gets camelized using "camelize" in Mojo::Util and prefixed with a namespace (defaulting to the applications class). While the action value is not changed at all, because of this both values are case sensitive.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # /bye -> {controller => 'foo', action => 'bye'} -> MyApp::Foo->bye
    $self->routes->route('/bye')->to(controller => 'foo', action => 'bye');
  }

  1;

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

  # Action
  sub bye {
    my $self = shift;

    # Render response
    $self->render(text => 'Good bye.');
  }

  1;

Controller classes are perfect for organizing code in larger projects. There are more dispatch strategies, but because controllers are the most commonly used ones they also got a special shortcut in the form of controller#action.

  # /bye -> {controller => 'foo', action => 'bye', mymessage => 'Bye'}
  $r->route('/bye')->to('foo#bye', mymessage => 'Bye');

During camelization - gets replaced with ::, this allows multi level controller hierarchies.

  # / -> {controller => 'foo-bar', action => 'hi'} -> MyApp::Foo::Bar->hi
  $r->route('/')->to('foo-bar#hi');

For security reasons the dispatcher will always check if the controller is actually a subclass of Mojolicious::Controller or Mojo before dispatching to it.

Route to class

You can use the namespace stash value to change the namespace of a whole route with all its children.

  # /bye -> MyApp::Controller::Foo::Bar->bye
  $r->route('/bye')
    ->to(namespace => 'MyApp::Controller::Foo::Bar', action => 'bye');

The controller is always appended to the namespace if available.

  # /bye -> MyApp::Controller::Foo::Bar->bye
  $r->route('/bye')->to('foo-bar#bye', namespace => 'MyApp::Controller');

  # /hey -> MyApp::Controller::Foo::Bar->hey
  $r->route('/hey')->to('Foo::Bar#hey', namespace => 'MyApp::Controller');

You can also change the default namespaces for all routes in the application with the router attribute "namespaces" in Mojolicious::Routes.

  $r->namespaces(['MyApp::Controller']);

Route to callback

The cb stash value, which won't be inherited by nested routes, can be used to bypass controllers and execute a callback instead.

  $r->route('/bye')->to(cb => sub {
    my $self = shift;
    $self->render(text => 'Good bye.');
  });

This technique is the foundation of Mojolicious::Lite, you can learn more about it from the included tutorial.

Placeholders and destinations

Extracted placeholder values will simply redefine older stash values if they already exist.

  # /bye -> {controller => 'foo', action => 'bar', mymessage => 'bye'}
  # /hey -> {controller => 'foo', action => 'bar', mymessage => 'hey'}
  $r->route('/:mymessage')
    ->to(controller => 'foo', action => 'bar', mymessage => 'hi');

One more interesting effect, a placeholder automatically becomes optional if there is already a stash value of the same name present.

  # / -> {controller => 'foo', action => 'bar', mymessage => 'hi'}
  $r->route('/:mymessage')
    ->to(controller => 'foo', action => 'bar', mymessage => 'hi');

  # /test/123     -> {controller => 'foo', action => 'bar', mymessage => 'hi'}
  # /test/bye/123 -> {controller => 'foo', action => 'bar', mymessage => 'bye'}
  $r->route('/test/:mymessage/123')
    ->to(controller => 'foo', action => 'bar', mymessage => 'hi');

This is also the case if multiple placeholders are right after another and not separated by other characters than /.

  # /           -> {controller => 'foo',   action => 'bar'}
  # /users      -> {controller => 'users', action => 'bar'}
  # /users/list -> {controller => 'users', action => 'list'}
  $r->route('/:controller/:action')
    ->to(controller => 'foo', action => 'bar');

Special stash values like controller and action can also be placeholders, which is very convenient especially during development, but should only be used very carefully, because every controller method becomes a potential route. All uppercase methods as well as those starting with an underscore are automatically hidden from the router and you can use "hide" in Mojolicious::Routes to add additional ones.

  # Hide "create" method in all controllers
  $r->hide('create');

This has already been done for all attributes and methods from Mojolicious::Controller.

More restrictive placeholders

A very easy way to make placeholders more restrictive are alternatives, you just make a list of possible values.

  # /bender -> {controller => 'foo', action => 'bar', name => 'bender'}
  # /leela  -> {controller => 'foo', action => 'bar', name => 'leela'}
  # /fry    -> undef
  $r->route('/:name', name => [qw(bender leela)])
    ->to(controller => 'foo', action => 'bar');

You can also adjust the regular expressions behind placeholders to better suit your needs. Just make sure not to use ^ and $ or capturing groups (...), because placeholders become part of a larger regular expression internally, (?:...) is fine though.

  # /23   -> {controller => 'foo', action => 'bar', number => 23}
  # /test -> undef
  $r->route('/:number', number => qr/\d+/)
    ->to(controller => 'foo', action => 'bar');

  # /23   -> undef
  # /test -> {controller => 'foo', action => 'bar', name => 'test'}
  $r->route('/:name', name => qr/[a-zA-Z]+/)
    ->to(controller => 'foo', action => 'bar');

This way you get easily readable routes and the raw power of regular expressions.

Formats

File extensions like .html and .txt at the end of a route are automatically detected and stored in the stash value format.

  # /foo      -> {controller => 'foo', action => 'bar'}
  # /foo.html -> {controller => 'foo', action => 'bar', format => 'html'}
  # /foo.txt  -> {controller => 'foo', action => 'bar', format => 'txt'}
  $r->route('/foo')->to(controller => 'foo', action => 'bar');

This for example allows multiple templates in different formats to share the same code.

  # /foo      -> {controller => 'foo', action => 'bar'}
  # /foo.html -> {controller => 'foo', action => 'bar', format => 'html'}
  $r->route('/foo')->to(controller => 'foo', action => 'bar');

Restrictive placeholders can also be used.

  # /foo.rss -> {controller => 'foo', action => 'bar', format => 'rss'}
  # /foo.xml -> {controller => 'foo', action => 'bar', format => 'xml'}
  # /foo.txt -> undef
  $r->route('/foo', format => [qw(rss xml)])
    ->to(controller => 'foo', action => 'bar');

Or you can just disable format detection, which gets inherited by nested routes and allows selective re-enabling.

  # /foo      -> {controller => 'foo', action => 'bar'}
  # /foo.html -> undef
  $r->route('/foo', format => 0)->to('foo#bar');

  # /foo      -> {controller => 'foo', action => 'bar'}
  # /foo.html -> undef
  # /baz      -> undef
  # /baz.txt  -> {controller => 'baz', action => 'yada', format => 'txt'}
  # /baz.html -> {controller => 'baz', action => 'yada', format => 'html'}
  # /baz.xml  -> undef
  my $inactive = $r->route(format => 0);
  $inactive->route('/foo')->to('foo#bar');
  $inactive->route('/baz', format => [qw(txt html)])->to('baz#yada');

Named routes

Naming your routes will allow backreferencing in many methods and helpers throughout the whole framework, most of them internally rely on "url_for" in Mojolicious::Controller for this.

  # /foo/abc -> {controller => 'foo', action => 'bar', name => 'abc'}
  $r->route('/foo/:name')->name('test')
    ->to(controller => 'foo', action => 'bar');

  # Generate URL "/foo/abc" for route "test"
  my $url = $self->url_for('test');

  # Generate URL "/foo/sebastian" for route "test"
  my $url = $self->url_for('test', name => 'sebastian');

  # Generate URL "http://127.0.0.1:3000/foo/sebastian" for route "test"
  my $url = $self->url_for('test', name => 'sebastian')->to_abs;

Nameless routes get an automatically generated one assigned that is simply equal to the route itself without non-word characters.

  # /foo/bar ("foobar")
  $r->route('/foo/bar')->to('test#stuff');

  # Generate URL "/foo/bar"
  my $url = $self->url_for('foobar');

To refer to the current route you can use the reserved name current or no name at all.

  # Generate URL for current route
  my $url = $self->url_for('current');
  my $url = $self->url_for;

To check or get the name of the current route you can use the helper "current_route" in Mojolicious::Plugin::DefaultHelpers.

  # Name for current route
  my $name = $self->current_route;

  # Check route name in code shared by multiple routes
  $self->stash(button => 'green') if $self->current_route('login');

HTTP methods

The method "via" in Mojolicious::Routes::Route allows only specific HTTP methods to pass.

  # GET /bye    -> {controller => 'foo', action => 'bye'}
  # POST /bye   -> undef
  # DELETE /bye -> undef
  $r->route('/bye')->via('GET')->to(controller => 'foo', action => 'bye');

  # GET /bye    -> {controller => 'foo', action => 'bye'}
  # POST /bye   -> {controller => 'foo', action => 'bye'}
  # DELETE /bye -> undef
  $r->route('/bye')->via('GET', 'POST')
    ->to(controller => 'foo', action => 'bye');

With one small exception, HEAD requests are considered equal to GET and content will not be sent with the response.

  # GET /test  -> {controller => 'bar', action => 'test'}
  # HEAD /test -> {controller => 'bar', action => 'test'}
  # PUT /test  -> undef
  $r->route('/test')->via('GET')->to(controller => 'bar', action => 'test');

WebSockets

With the method "websocket" in Mojolicious::Routes::Route you can restrict access to WebSocket handshakes, which are normal GET requests with some additional information.

  # /echo (WebSocket handshake)
  $r->websocket('/echo')->to(controller => 'foo', action => 'echo');

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

  # Action
  sub echo {
    my $self = shift;
    $self->on(message => sub {
      my ($self, $msg) = @_;
      $self->send("echo: $msg");
    });
  }

  1;

The connection gets established when you respond to the WebSocket handshake request with a 101 response status, which happens automatically if you subscribe to an event with "on" in Mojolicious::Controller or send a message with "send" in Mojolicious::Controller right away.

Bridges

Bridge routes created with the method "bridge" in Mojolicious::Routes::Route can be used to share code with multiple nested routes, because unlike normal nested routes, they result in additional dispatch cycles when they match.

  # /foo     -> undef
  # /foo/bar -> {controller => 'foo', action => 'baz'}
  #             {controller => 'foo', action => 'bar'}
  my $foo = $r->bridge('/foo')->to(controller => 'foo', action => 'baz');
  $foo->route('/bar')->to(action => 'bar');

The actual bridge code needs to return a true value or the dispatch chain will be broken, this makes bridges a very powerful tool for authentication.

  # /foo     -> undef
  # /foo/bar -> {cb => sub {...}}
  #             {controller => 'foo', action => 'bar'}
  my $foo = $r->bridge('/foo')->to(cb => sub {
    my $self = shift;

    # Authenticated
    return 1 if $self->req->headers->header('X-Bender');

    # Not authenticated
    $self->render(text => "You're not Bender.");
    return undef;
  });
  $foo->route('/bar')->to(controller => 'foo', action => 'bar');

Broken dispatch chains can be continued by calling the method "continue" in Mojolicious::Controller, this allows for example non-blocking operations to finish before reaching the next dispatch cycle.

  # /foo     -> undef
  # /foo/bar -> {cb => sub {...}}
  #          -> {controller => 'foo', action => 'bar'}
  my $foo = $r->bridge('/foo')->to(cb => sub {
    my $self = shift;

    # Wait 3 seconds and then give visitors a 50% chance to continue
    Mojo::IOLoop->timer(3 => sub {

      # Loser
      return $self->render(text => 'No luck.') unless int rand 2;

      # Winner
      $self->continue;
    });

    return undef;
  });
  $foo->route('/bar')->to(controller => 'foo', action => 'bar');

More convenient routes

From the tutorial you should already know Mojolicious::Lite routes, which are in fact just a small convenience layer around everything described above and accessible through methods like "get" in Mojolicious::Routes::Route as part of the normal router.

  # POST /foo -> {controller => 'foo', action => 'abc'}
  $r->post('/foo')->to(controller => 'foo', action => 'abc');

  # PATCH /bar -> {controller => 'foo', action => 'bar', test => 23}
  $r->patch('/bar')->to('foo#bar', test => 23);

  # GET /baz -> {template => 'foo/bar'}
  $r->get('/baz')->to(template => 'foo/bar');

  # * /yada.txt  -> {controller => 'foo', action => 'yada', format => 'txt'}
  # * /yada.json -> {controller => 'foo', action => 'yada', format => 'json'}
  $r->any('/yada' => [format => [qw(txt json)]])->to('foo#yada');

  # GET   /foo/bar  -> {controller => 'foo', action => 'bar'}
  # PUT   /foo/baz  -> {controller => 'foo', action => 'baz'}
  # PATCH /foo      -> {controller => 'foo', action => 'yada'}
  my $foo = $r->any('/foo')->to('foo#');
  $foo->get('/bar')->to('#bar');
  $foo->put('/baz')->to('#baz');
  $foo->patch->to('#yada');

This makes the process of growing your Mojolicious::Lite prototypes into full Mojolicious applications very straightforward.

  # POST /bar
  $r->post('/bar' => sub {
    my $self = shift;
    $self->render(text => 'Just like a Mojolicious::Lite action.');
  });

Even the more abstract concepts are available with methods like "under" in Mojolicious::Routes::Route.

  # GET  /yada
  # POST /yada
  my $yada = $r->under('/yada');
  $yada->get(sub {
    my $self = shift;
    $self->render(text => 'Hello.');
  });
  $yada->post(sub {
    my $self = shift;
    $self->render(text => 'Go away.');
  });

Hooks

Hooks operate outside the routing system and allow you to extend the framework itself by sharing code with all requests indiscriminately through "hook" in Mojolicious, which makes them a very powerful tool especially for plugins.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Check all requests for a "/test" prefix
    $self->hook(before_dispatch => sub {
      my $c = shift;
      $c->render(text => 'This request did not reach the router.')
        if $c->req->url->path->contains('/test');
    });

    # These will not be reached if the hook above renders a response
    my $r = $self->routes;
    $r->get('/welcome')->to('foo#welcome');
    $r->post('/bye')->to('foo#bye');
  }

  1;

Post-processing the response to set additional headers is a very common use.

  # Make sure static files are cached
  $self->hook(after_static => sub {
    my $c = shift;
    $c->res->headers->cache_control('max-age=3600, must-revalidate');
  });

Same for pre-processing the request.

  # Allow "_method" query parameter to override request method
  $self->hook(before_dispatch => sub {
    my $c = shift;
    return unless my $method = $c->req->url->query->param('_method');
    $c->req->method($method);
  });

Or more advanced extensions to add monitoring to your application.

  # Forward exceptions to a web service
  $self->hook(after_dispatch => sub {
    my $c = shift;
    return unless my $e = $c->stash('exception');
    $c->ua->post('https://example.com/bugs' => form => {exception => $e});
  });

You can even extend much of the core functionality.

  # Make controller object available to actions as $_
  $self->hook(around_action => sub {
    my ($next, $c, $action, $last) = @_;
    local $_ = $c;
    return $next->();
  });

  # Pass route name as argument to actions
  $self->hook(around_action => sub {
    my ($next, $c, $action, $last) = @_;
    return $c->$action($c->current_route);
  });

For a full list of available hooks see "HOOKS" in Mojolicious.

Shortcuts

You can also add your own shortcuts with "add_shortcut" in Mojolicious::Routes to make route generation more expressive.

  # Simple "resource" shortcut
  $r->add_shortcut(resource => sub {
    my ($r, $name) = @_;

    # Generate "/$name" route
    my $resource = $r->route("/$name")->to("$name#");

    # Handle POST requests
    $resource->post->to('#create')->name("create_$name");

    # Handle GET requests
    $resource->get->to('#show')->name("show_$name");

    # Handle OPTIONS requests
    $resource->options(sub {
      my $self = shift;
      $self->res->headers->allow('POST, GET, OPTIONS');
      $self->render(data => '', status => 204);
    });

    return $resource;
  });

  # POST    /user -> {controller => 'user', action => 'create'}
  # GET     /user -> {controller => 'user', action => 'show'}
  # OPTIONS /user
  $r->resource('user');

Shortcuts can lead to anything, routes, bridges or maybe even both. And watch out for quicksand!

Introspection

The command Mojolicious::Command::routes can be used from the command line to list all available routes together with name and underlying regular expressions.

  $ ./myapp.pl routes -v
  /foo/:name  ....  POST  fooname  ^/foo/([^/\.]+))(?:\.([^/]+)$)?
  /bar        B...  *     bar      ^/bar
    +/baz     ...W  GET   baz      ^/baz(?:\.([^/]+)$)?
  /yada       ....  *     yada     ^/yada(?:\.([^/]+)$)?

ADVANCED

Less commonly used and more powerful features.

IRIs

IRIs are handled transparently, that means paths are guaranteed to be unescaped and decoded from bytes to characters.

  # GET /☃ (unicode snowman) -> {controller => 'foo', action => 'snowman'}
  $r->get('/☃')->to('foo#snowman');

Rearranging routes

Until the first request has been handled, all routes can still be moved around or even removed with methods like "add_child" in Mojolicious::Routes::Route and "remove" in Mojolicious::Routes::Route. Especially for rearranging routes created by plugins this can be very useful.

  # GET /example/show -> {controller => 'example', action => 'show'}
  my $show = $r->get('/show')->to('example#show');
  $r->any('/example')->add_child($show);

  # Nothing
  $r->get('/secrets/show')->to('secrets#show')->name('show_secrets');
  $r->find('show_secrets')->remove;

To find routes by their name you can use "find" in Mojolicious::Routes::Route.

Conditions

Sometimes you might need a little more power, for example to check the User-Agent header in multiple routes. This is where conditions come into play, they are basically router plugins.

  # Simple "User-Agent" condition
  $r->add_condition(
    agent => sub {
      my ($route, $c, $captures, $pattern) = @_;

      # User supplied regular expression
      return undef unless $pattern && ref $pattern eq 'Regexp';

      # Match "User-Agent" header and return true on success
      my $agent = $c->req->headers->user_agent;
      return 1 if $agent && $agent =~ $pattern;

      # No success
      return undef;
    }
  );

  # /firefox_only (Firefox) -> {controller => 'foo', action => 'bar'}
  $r->get('/firefox_only')->over(agent => qr/Firefox/)->to('foo#bar');

The method "add_condition" in Mojolicious::Routes registers the new condition in the router, while "over" in Mojolicious::Routes::Route actually applies it to the route.

Condition plugins

You can also package your conditions as reusable plugins.

  # Plugin
  package Mojolicious::Plugin::WerewolfCondition;
  use Mojo::Base 'Mojolicious::Plugin';

  use Astro::MoonPhase;

  sub register {
    my ($self, $app) = @_;

    # Add "werewolf" condition
    $app->routes->add_condition(werewolf => sub {
      my ($route, $c, $captures, $days) = @_;

      # Keep the werewolves out!
      return undef if abs(14 - (phase(time))[2]) > ($days / 2);

      # It's ok, no werewolf
      return 1;
    });
  }

  1;

Now just load the plugin and you are ready to use the condition in all your applications.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Plugin
    $self->plugin('WerewolfCondition');

    # /hideout (keep them out for 4 days after full moon)
    $self->routes->get('/hideout')->over(werewolf => 4)
      ->to(controller => 'foo', action => 'bar');
  }

  1;

Embedding applications

You can easily embed whole applications simply by using them instead of a controller. This allows for example the use of the Mojolicious::Lite domain specific language in normal Mojolicious controllers.

  # Controller
  package MyApp::Bar;
  use Mojolicious::Lite;

  # /hello
  get '/hello' => sub {
    my $self = shift;
    my $name = $self->param('name');
    $self->render(text => "Hello $name.");
  };

  1;

With the method "detour" in Mojolicious::Routes::Route which is very similar to "to" in Mojolicious::Routes::Route, you can allow the route to partially match and use only the remaining path in the embedded application, the base path will be passed along in the path stash value.

  # /foo/*
  $r->any('/foo')->detour('bar#', name => 'Mojo');

A minimal embeddable application is nothing more than a subclass of Mojo, containing a handler method accepting Mojolicious::Controller objects.

  package MyApp::Bar;
  use Mojo::Base 'Mojo';

  sub handler {
    my ($self, $c) = @_;
    $c->res->code(200);
    my $name = $c->param('name');
    $c->res->body("Hello $name.");
  }

  1;

You can also just use Mojolicious::Plugin::Mount to mount whole self-contained applications under a domain and/or prefix.

  use Mojolicious::Lite;

  # Whole application mounted under "/prefix"
  plugin Mount => {'/prefix' => '/home/sri/myapp.pl'};

  # Mount application with subdomain
  plugin Mount => {'test.example.com' => '/home/sri/myapp2.pl'};

  # Normal route
  get '/' => sub { shift->render(text => 'Hello World!') };

  app->start;

Application plugins

Embedding Mojolicious applications is easy, but it gets even easier if you package the whole thing as a self-contained reusable plugin.

  # Plugin
  package Mojolicious::Plugin::MyEmbeddedApp;
  use Mojo::Base 'Mojolicious::Plugin';

  sub register {
    my ($self, $app) = @_;

    # Automatically add route
    $app->routes->any('/foo')->detour(app => EmbeddedApp::app());
  }

  package EmbeddedApp;
  use Mojolicious::Lite;

  get '/bar' => 'bar';

  1;
  __DATA__
  @@ bar.html.ep
  Hello World!

The app stash value, which won't be inherited by nested routes, can be used for already instantiated applications. Now just load the plugin and you're done.

  # Application
  package MyApp;
  use Mojo::Base 'Mojolicious';

  sub startup {
    my $self = shift;

    # Plugin
    $self->plugin('MyEmbeddedApp');
  }

  1;

MORE

You can continue with Mojolicious::Guides now or take a look at the Mojolicious wiki, which contains a lot more documentation and examples by many different authors.

SUPPORT

If you have any questions the documentation might not yet answer, don't hesitate to ask on the mailing-list or the official IRC channel #mojo on irc.perl.org.