“动态”在莫约利西斯的路线
我想在我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在运行时添加路由这似乎是一个好方法(尽管您可能应该在覆盖路由之前检查路由是否存在)。您还可以将其作为带有通配符占位符的包罗万象的内容,然后稍后再传递请求。
http://mojolicio.us/perldoc/Mojolicious/Guides/Routing#Wildcard_Placeholders
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