如何访问 Mojolicious 模型中的会话数据

How to access session data in Mojolicious model

下面是一个示例 Mojolicious (6.14) 应用程序...对于 $_[0] 和其他不尽如人意的做法感到抱歉;我试着让它变得紧凑。

package ScopeTest;
use Mojo::Base 'Mojolicious';

sub startup {
  my $app = shift;

  $app->helper( hello    => sub { "Hello!" } );
  $app->helper( username => sub { $_[0]->session('username'); } );
  $app->helper( model    => sub { ScopeTest::Model->new( app => $_[0]->app ) } );
  $app->helper( hasPerm  => sub { $_[0]->model->hasPerm( @_ ) } );

  $app->routes->get('/alice')->to('controller#alice');
  $app->routes->get('/carol')->to('controller#carol');
  $app->routes->get('/steve')->to('controller#steve');
}

##############################
package ScopeTest::Controller;
use Mojo::Base 'Mojolicious::Controller';

sub alice { $_[0]->session( username => "alice" ); $_[0]->render_message() }
sub carol { $_[0]->session( username => "carol" ); $_[0]->render_message() }
sub steve { $_[0]->session( username => "steve" ); $_[0]->render( text =>
    sprintf "%s: %s\n", $_[0]->username, $_[0]->model->update_db ? 'Okay' : 'Fail' ) }

sub render_message { $_[0]->render( text =>
    sprintf "%s: %s\n", $_[0]->username, $_[0]->hasPerm('canLogin') ? 'Okay' : 'Fail' ) }

##############################
package ScopeTest::Model;
use Mojo::Base -base;

has 'app';

my %perms = ( alice => [ qw{ canLogin } ],
              carol => [ ],
              steve => [ qw{ canUpdateDB } ] );

sub hasPerm {
    my ( $self, $perm ) = @_;
    no warnings 'uninitialized';

    $self->app->log->debug("app->hello            = " . $self->app->hello                 );   # OKAY
    $self->app->log->debug("app->username         = " . $self->app->username              );   # FAILS
    $self->app->log->debug("session('username')   = " . $self->app->session('username')   );   # FAILS
    $self->app->log->debug("session->{'username'} = " . $self->app->session->{'username'} );   # FAILS

    my $username;   # = $self->app->username;
    return grep { $_ eq $perm } @{ $perms{$username} };
}

sub update_db {
    my ( $self, $data ) = @_;
    $self->hasPerm('canUpdateDB') or return;
    # else ...
    return 1;
}

1;

虽然 $self->app->log->debug()$self->app->dumper() 以及其他帮助者做正确的事,但 $self->app->session 却没有。

我知道传递 $app 被认为不太理想,但我希望以上内容至少可以工作...

除了一遍又一遍地传递用户名(这是一个玩具示例;真正的应用程序有几十种不同的方法,有时会相互调用,等等)是否有一种更简洁的方法来从型号 class?

PS — 在你说 Model->new(username => $self->session('username') 之前,这意味着知道 先验 ,我将需要哪些会话变量,以及在构造函数和属性列表中枚举它们;我希望如果我整个 $app(甚至 $app->session)都通过了,我可以让事情经得起未来的考验。

谢谢!

我犯的错误是:"session"信息与应用程序没有关联;它与控制器关联:

$app->helper( model => sub { ScopeTest::Model->new( ctrl => $_[0] ) } );

然后:

package ScopeTest::Model;
use Mojo::Base -base;

has 'ctrl';

...
$self->ctrl->app->log->debug("username = " . $self->ctrl->username );

是的,我知道将 Controller 传递给 Model 仍然不是最佳选择,但这至少解释了为什么我之前根本无法让它工作...