桥处理程序无法访问存储数据

时间:2016-02-11 06:31:25

标签: perl mojolicious

我在使用Mojolicious编写的webapp中有以下代码,并且它无法按预期工作:桥接处理程序无法获取从路由派生的正确存储数据(获取undef),因此其余代码失败,但是,任何路由处理程序中的$ self-> stash('city')的调试输出都是预期的。

...
# Router.
my $r = $self->routes->bridge->to('Main#common');
$r->route('/')->to('Main#index')->name('start');
$r->route('/:region/:city/category/:id')->to('Main#list_category')->name('list_category');
$r->route('/:region/:city/part/:id/:name')->to('Main#show_part')->name('show_part');
...
# Controller.
sub common
{
    my $self=shift;
    my $db=$self->db;
    my $city=$self->stash('city');
    my $region=$self->db->selectrow_hashref('select * from region where LOWER(translit)=? ORDER BY region_id LIMIT 1',undef,$city);
    say "City=$city.";
    if(!$region)
    {
        $region={};
    }
    $self->stash(region=>$region);
    return 1;
}
...

1 个答案:

答案 0 :(得分:1)

I think it's correct behavior.
Look at this code. Placeholder is added when the appropriate route is taken to the processing, i.e., step by step.

Really, look at you routes.

Files = string[]{"a", "b", "c"};

I can't understand what behavior you expect when go to route /. Sub my $r = $self->routes->bridge->to('Main#common'); $r->route('/')->to('Main#index')->name('start'); $r->route('/:region/:city/category/:id')->to('Main#list_category')->name('list_category'); $r->route('/:region/:city/part/:id/:name')->to('Main#show_part')->name('show_part'); will be invoked in this case. There are no value for placeholder common!

So, correct solution for your routes must look like this:

city

By the way,

starting from Mojolicious version 6.0 my $r = $self->routes; $r->route('/')->to('Main#index')->name('start'); my $r_city = $r->bridge('/:region/:city/')->to('Main#common'); $r_city->route('/category/:id')->to('Main#list_category')->name('list_category'); $r_city->route('/part/:id/:name')->to('Main#show_part')->name('show_part'); was deprecated to favor bridge. So, you need to replace under on bridge.

But, if you very-very want to have value of placeholder under in city function, you may look at this two line.
You need to write this BAD code in common sub:

common

Print sub common { my $self = shift; my $stack = $self->match->stack; warn $self->dumper($stack); ... } and you understand how to get value of placeholder $stack.