我正在阅读Mojolicious::Guides::Growing部分,它告诉您如何将 Mojolicious::Lite 发展为“组织良好”的 cpan 可上传应用程序。首先,它告诉您将 M::L 应用程序拆分为启动脚本和应用程序类。
package MyApp;
use Mojo::Base 'Mojolicious';
use MyUsers;
sub startup {
my $self = shift;
# ...auth stuff omitted...
my $r = $self->routes;
$r->any('/' => sub {
my $self = shift;
my $user = $self->param('user') || '';
my $pass = $self->param('pass') || '';
return $self->render unless $self->users->check($user, $pass);
$self->session(user => $user);
$self->flash(message => 'Thanks for logging in.');
$self->redirect_to('protected');
} => 'index');
$r->get('/protected' => sub {
my $self = shift;
return $self->redirect_to('index') unless $self->session('user');
});
$r->get('/logout' => sub {
my $self = shift;
$self->session(expires => 1);
$self->redirect_to('index');
});
}
1;
这对我来说很有意义。但是接着说这个应用类可以进一步重构为一个带有动作的控制器类,应用类本身可以简化为路由信息:
package MyApp::Login;
use Mojo::Base 'Mojolicious::Controller';
sub index {
my $self = shift;
my $user = $self->param('user') || '';
my $pass = $self->param('pass') || '';
return $self->render unless $self->users->check($user, $pass);
$self->session(user => $user);
$self->flash(message => 'Thanks for logging in.');
$self->redirect_to('protected');
}
sub protected {
my $self = shift;
return $self->redirect_to('index') unless $self->session('user');
}
sub logout {
my $self = shift;
$self->session(expires => 1);
$self->redirect_to('index');
}
1;
package MyApp;
use Mojo::Base 'Mojolicious';
use MyUsers;
sub startup {
my $self = shift;
# ...auth stuff omitted...
my $r = $self->routes;
$r->any('/')->to('login#index')->name('index');
$r->get('/protected')->to('login#protected')->name('protected');
$r->get('/logout')->to('login#logout')->name('logout');
}
1;
我不明白为什么这优于路由和动作混合的“混合”版本,因为现在为了在控制器中使用 redirect_to() 在动作之间重定向,您需要以不同的方式查看路由信息文件,如果要更改 url,则必须在两个不同的文件中进行,而不是在一个文件中进行。这个:
$r->get('/protected' => sub {
my $self = shift;
return $self->redirect_to('index') unless $self->session('user');
});
变成:
sub protected {
my $self = shift;
return $self->redirect_to('index') unless $self->session('user');
}
$r->get('/protected')->to('login#protected')->name('protected');
在两个不同的文件中有 4 次“受保护”一词(尽管我不确定名称(“受保护”)是做什么的)。
顺便说一下,在 Web 开发方面,我是一个完全的新手。