Why are separate routing and controller actions mojolicious?

I read the Mojolicious :: Guides :: Growing section , where he tells you how to grow Mojolicious :: Lite in a “well-organized” cpan, a downloadable application. First, it tells you to break the M :: L application into a script run and application class.

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;

That makes sense to me. But then it goes on to say that this application class can be reorganized into a controller class with actions, and the application class itself can be reduced to routing information:

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

"protected" 4 ( , "" ).

, , , -.

+5
1

; , .

, ; . , 1000 . , , , 100 +.

, URL- . Mojolicious , .

+8

All Articles