【问题标题】:Can '->to()' be used in Mojolicious::Lite?'->to()' 可以在 Mojolicious::Lite 中使用吗?
【发布时间】:2018-10-30 22:49:33
【问题描述】:

我想在 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"

我是不是搞错了?

【问题讨论】:

  • 当你这样做并调用路由时会发生什么?
  • @simbabque - 查看编辑
  • 如果您可以发布调试日志的相关部分,那将非常有帮助。 Mojolicious::Lite 确实允许调用->to()get ...app->routes->get(...) 相同),但您必须确保 Mojolicious 找到并使用正确的控制器。请注意,回调不是控制器或控制器动作,所以->to('#y') 在这里找不到任何东西——考虑使用单独的控制器类。
  • @amon - 我添加了日志输出并将代码分离到一个控制器包中

标签: perl mojolicious


【解决方案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() 相同。)

【讨论】:

  • 这太酷了。谢谢。 “get '/x' => { controller => 'Route', action => 'bar' };”在哪里记录在案?只是好奇。
  • TBH 它没有明确记录在一个地方,我只是阅读了源代码。 Mojo::Lite中的get函数提到它相当于Router上的get,它使用any方法,其中提到我们可以使用hashrefs作为默认的stash值(其中controller和action是特殊的存储密钥)。
猜你喜欢
  • 1970-01-01
  • 2015-10-06
  • 2012-10-06
  • 1970-01-01
  • 2011-03-04
  • 2015-09-23
  • 1970-01-01
  • 2011-10-25
  • 2017-07-04
相关资源
最近更新 更多