我正在閱讀Mojolicious::Guides::Growing這一部分,它告訴你如何將Mojolicious :: Lite發展成一個「組織良好」的可上載應用程序。首先,它告訴您將M :: L應用程序拆分爲啓動腳本和應用程序類。爲什麼單獨路由和控制器操作在mojolicious?
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()之間重定向動作,您需要查看不同文件中的路由信息,並且如果您想要改變一個網址,你必須在兩個不同的文件而不是一個。這:
$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開發方面,我是一個完全新手。
OOhhhh,我沒有意識到,redirect_to('foo')將'foo'解釋爲名稱而不是路徑'/ foo',並且M :: L get/post/any/etc函數會自動創建的名稱。這一切都有道理,謝謝。 – user1481