I've created a helper for accessing my Model like this:

$self->helper(model => sub { my $c = shift; state $model = Model->new(pg =>
$c->pg, ua => $c->ua) });


I want my Model class to have access to the current session id
($c->session('id')) for every DB query it makes.  My understanding is that
I should *not* pass the controller to the Model like this (because you want
M-C separation):

$self->helper(model => sub { my $c = shift; Model->new(pg => $c->pg, ua =>
$c->ua, app=> $c) });
(We want to avoid initializing a new Model instance on every request
anyway, don't we?)


So, how can I make my Model class always aware of some specific controller
state, like the session?  It seems silly to pass the session id for every
method, like this:

$c->model->method1($id, $other, $parameters);
$c->model->method2($id, $other, $parameters);
$c->model->method3($id, $other, $parameters);


Is there a good way to ensure that the Model always has access to some
controller state, without having to pass that state on every method call?

Right now my solution is to use a hook:

$self->app->hook(before_routes => sub {
    my $c = shift;
    $c->model->id($c->session('id')) if $c->session('id');
});


Now every call to the Model method will be able to call $self->id and have
access to that piece of the controller state.  My Model needs access to the
session id so that it can restrict the results of database queries to data
that is appropriate for the current user only.

Is that a good way to do this?  Is there a better way?  Or should I really
pass that controller state explicitly at every method call?

-- 
You received this message because you are subscribed to the Google Groups 
"Mojolicious" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/mojolicious.
For more options, visit https://groups.google.com/d/optout.

Reply via email to