我想在Mojolicious :: Lite应用程序中使用适量的转发到其他控制器。
我以为我可以使用->to
(docs)做类似
(get '/x')->to('Route#bar');
get '/y' => sub {
my $c = shift;
$c->render(text => 'here')
} => 'y';
app->start;
控制器包中的代码如下所示:
package Route::Controller::Route;
use Mojo::Base 'Mojolicious::Controller';
sub bar {
my $self = shift;
$self->render(json => { hello => 'simone' });
}
1;
但它似乎不起作用http://localhost:3000/x
返回404“页面未找到......”和http://localhost:3000/y
工作正常
日志转储如下所示:
[Wed May 23 11:39:47 2018] [debug] Template "route/bar.html.ep" not found
[Wed May 23 11:39:47 2018] [debug] Template "not_found.development.html.ep" not found
[Wed May 23 11:39:47 2018] [debug] Template "not_found.html.ep" not found
[Wed May 23 11:39:47 2018] [debug] Rendering cached template "mojo/debug.html.ep"
[Wed May 23 11:39:47 2018] [debug] Rendering cached template "mojo/menubar.html.ep"
我出错了吗?
答案 0 :(得分:1)
如果将控制器放在一个类中并告诉Mojolicious在哪里找到该控制器,这确实有效。默认情况下,Lite应用程序不会在任何路径名称空间中搜索控制器。
use Mojolicious::Lite;
push app->routes->namespaces->@*, 'Route::Controller';
(get '/x')->to('Route#bar');
app->start;
package Route::Controller::Route;
use Mojo::Base 'Mojolicious::Controller';
sub bar {
my $self = shift;
$self->render(json => { hello => 'simone' });
}
1;
当调用perl test.pl get /x
时,我看到了这个调试输出:
[Wed May 23 12:01:14 2018] [debug] GET "/x"
[Wed May 23 12:01:14 2018] [debug] Routing to controller "Route::Controller::Route" and action "bar"
[Wed May 23 12:01:14 2018] [debug] 200 OK (0.000467s, 2141.328/s)
{"hello":"simone"}
如果你没有使用方便的Route#bar
语法,你也可以将路线指定为:
get '/x' => { controller => 'Route', action => 'bar' };
(给get
提供hashref与使用这些参数在新路由上调用->to()
相同。)