perlmojoliciousmojolicious-lite

Can I forward to action in same controller in Mojolicious


If I split my application with Controller classes I can do

 get '/foo/bar' => { controller => 'Foo', action => 'bar' };

can I do the same if my action is inside the same Mojolicious::Lite file?

For now I do

sub foobar {
    my $c = shift;
    ...
}

get '/' => sub { foobar(@_) };

but I'd like to do

get '/' => { action => 'foobar' };

for consistency and ease of splitting later should I decide to do so, while keeping the general Mojolicious::Lite structure (i.e: single file).

How can this be done?


Solution

  • While Mojolicious::Lite is a very simple wrapper, any subs defined within the Lite script will not be controller methods but application methods. There's not really a way to make them controller methods except by defining a controller, which is totally possible even in a lite app (very simple wrapper) but would make it not-so-lite. The other direction is easily possible though; you can have anonymous subroutines as actions in a full app. You could also write your actions as helpers, which can then be called simply from either an anonymous subroutine or a controller action. Either of these would probably not be great code organization for a full app.

    The main takeaway in any case is that the contents of a Mojolicious::Lite script are equivalent to the startup sub of a full app, not a controller.