Search code examples
perlmojolicious

Mojolicious and packaged routes?


Mojolicious has a routes object named Mojolicious::Routes. I would like to create one of these outside of my app, independent of it so I could export these routes and import them into my app..

use Mojolicious::Routes;

sub _gen_route {
  my $r = Mojolicious::Routes->new;
  $r->get('/foo')->to(sub{ print "hello, foo" });
  $r;
}

Then in a Mojo application

sub startup {
  my $self = shift;
  my $r = shift;

  $r->get('/bar')->to(sub{ print "hello, bar" });

  $r->import_router(_gen_route())
}

Is there anyway to compose routers? Ie., package up a route and import it into Apps router?


Solution

  • You probably want to create a Mojolicious::Plugin. The plugin's register method is called on startup and has access to the app and through it to its routes.

    So, your route-adding module would look like this:

    package MyRouteGen;
    use Mojo::Base 'Mojolicious::Plugin';
    
    sub register {
      my ($self, $app, $conf) = @_;
      $name = ($conf && defined $conf->{'name'}) ? $conf->{'name'} : 'foo'; 
      return $app->routes->get('/foo')
                         ->to(sub{ 
                                shift->render(text => "hello, $name")
                            });
     }
    

    Then in a Mojo application:

    sub startup {
     my $app = shift;
     $app->plugin('MyRouteGen', { name => 'baz' });
     $app->get('/bar')->to(sub{ print "hello, bar" });
     ...
    }