“动态”在莫约利西斯的路线

发布于 2024-11-04 23:40:28 字数 630 浏览 0 评论 0原文

我想在我的 Mojolicious 应用程序中实现类似“动态”路线的功能。我有一些预定义的“静态”路由和一个带有 URL 别名的数据库表: '/alias' -> '/网址'。现在我正在动态定义路线,它看起来像这样:

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 ); 
  } 

但是还有更好的方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

并安 2024-11-11 23:40:28

您在运行时添加路由这似乎是一个好方法(尽管您可能应该在覆盖路由之前检查路由是否存在)。您还可以将其作为带有通配符占位符的包罗万象的内容,然后稍后再传递请求。

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

$r->get('/(*everything)' )->to('mycontroller#aliases');

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');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文