[Catalyst] Catalyst::Component/Model Instances and Attributes per Request

Tomas Doran bobtfish at bobtfish.net
Sun Jul 18 22:47:31 GMT 2010


On 18 Jul 2010, at 21:42, Alejandro Imass wrote:
> Ok. already! ;-)  I have a big bump in my forehead from all this
> headbanging. With the headache and all I think I finally
> understand...I hope... In my case I need a model that creates an
> object to handle every request individually so:

Yep, you got it.

Couple of slight clarifications / corrections below.

> 1) Create a very thin layer that will be the instance. Having: BEGIN
> {extends 'Catalyst::Model'; }
> 2) Override ACCEPT_CONTEXT

ACCEPT_CONTEXT is optional (so you're not overriding it).

> 3) In this sub, create an object of type foo and return _that_  
> instead of $self
>
> So my Model instance is in fact a factory.

Just so.

> This way I don't have to
> worry about the attributes because each controller will have it's own
> copy of foo. Is this close?

Yes. In fact, if you just write an ACCEPT_CONTEXT method, then every  
call to $c->model('Foo') will factory a new instance for you. Which  
may or may not imply each controller (or event different parts of the  
same controller) gets a different one, depending on how you structure  
your controller code.

> The Definitive Guide to Catalyst has an extension to the Catalyst
> Cookbook, in page 255 talks about Catalyst::Model::Factory which might
> be another way of doing what I want, but perhaps overkill for my
> simple problem.

No, Catalyst::Model::Factory does _exactly_ and _only_ this for you,  
so you probably/possibly want to use that rather than writing it  
yourself :)

Another possibility it's well worth looking into if appropriate is  
Catalyst::Component::InstancePerContext, which handles all of the  
logic to put the instance which is generated by the factory into the  
stash for you, so that subsequent requests to $c->model('Foo') in the  
same request get back the same instance...

In some cases (if you're changing the state of this model during a  
request) then that's likely what you're looking for.

Cheers
t0m






More information about the Catalyst mailing list