[Catalyst] Store something in the stash at startup

Tomas Doran bobtfish at bobtfish.net
Wed Aug 18 10:04:02 GMT 2010

On 18 Aug 2010, at 04:07, Charlie Garrison wrote:
>> I.e. if you are saying [% c.model('Foo').thing %] or [% c.foo.thing  
>> %] then this is less flexible (as you can't override foo for part  
>> of your site) than $c->stash(foo => $c->model('Foo')) in your perl  
>> code, then [% foo.thing %] in your template.
> I'm not sure I understand why it's less flexible. I use attributes  
> on the context object to store objects that are needed *everywhere*  
> in the app. I was following the logic of $c->user which stores the  
> current $user. The objects stored in the context attributes are  
> still models, and as such can be flexible.

Yes, this is a clear example where I'd recommend stashing the user  
also, rather than calling on $c->user (or [% c.user %]

The controller is there to be a mediation layer between the model and  
the view, such that the view doesn't have too much (well, hopefully  
any) data codified into it about 'how' (e.g. how to get a user  
object), it just knows 'what' (e.g. what methods on the user object it  
is passed to call to get the username).. This allows you to swap out  
the user object in some way, or reuse the template in a context not  
initially imagined.. If the data access is hard coded into the  
template, this is much less easy.

For a more practical example, with [% c.user %] you will _always_,  
_always_ be showing the currently logged in user. If the template is  
referring to [% user %] then you can change the apparent user by  
putting something different in the stash.

This could be pretty helpful, imagine an administrator to your site,  
and giving them the facility to see something 'as the user would'. To  
achieve this in your scheme, you're going to have to either (a) add  
logic to your template, or (b) play silly buggers with $c->user,  
whereas if the template doesn't know or care where the user comes  
from, it _just works_, without any need to think about it - if the  
user (and other details) are all stashed, then the admin part of your  
app can just fiddle with the stash, then do a $c->go to the page a  
normal user would see..

Does this make sense how this would work? I'm not saying you want this  
facility _right now_, just that when you come to want it, it's nice if  
your template is already flexible - which is why I'd try to have the  
controller pass all the data your template is going to operate on into  
the template, rather than have the template reaching into the model..

> It didn't make sense to me (& in one case had race-condition, don't  
> recall specifics)



More information about the Catalyst mailing list