8

I would like to implement something like "dynamic" routes in my Mojolicious app. I have some pre-defined "static" routes and a DB table with URL aliases: '/alias' -> '/URL'. Now I'm defining routes on-the-fly and it looks like this:

before_dispatch => sub { 
  my ($self, $controller) = @_; 
  my $path = $controller->tx->req->url->path->to_string; 
  if ( my $alias = $controller->app->model->alias->find({ alias => $path }) ) { 
    my $match = Mojolicious::Routes::Match->new( get => $alias->{uri} ); 
    my $routes = $controller->app->routes; 
    $match->match( $routes ); 
    $routes->route( $path )->to( $match->captures ); 
  } 

But is there any better way?

deadboy
  • 81
  • 2

1 Answers1

4

You are adding routes at runtime which seems a good approach (although you should probably check if a route exists before overriding it). You could also do it as a catchall with a wildcard placeholder then handoff the request a bit later on.

http://mojolicio.us/perldoc/Mojolicious/Guides/Routing#Wildcard_Placeholders

$r->get('/(*everything)' )->to('mycontroller#aliases');
CoffeeMonster
  • 2,160
  • 4
  • 20
  • 34
  • You don't need to check if a route exists if you put the catchall at the bottom of your routes list. The routes are tried sequentially and the first match is used. – Christopher Causer Aug 10 '17 at 09:18