[Catalyst] Model/Schema questions

Matt S Trout dbix-class at trout.me.uk
Sun May 21 21:00:27 CEST 2006


Patryk Dwórznik wrote:
> Hi,
> I would really appreciate if someone could explain me how to properly 
> use a DBIC model in a Catalyst application.
> 
> I've got a schema and a model class (this is almost copy&pasted from 
> Catalyst manual) with a function doing some transaction in it. What I 
> want to do in the following controller is to create a user object using 
> the function from MyApp::Model::DB::User. Two problems emerge:
>  - how to access model classes from controller?

$c->model is correct for this.

>  - how to get  the schema object in model classes?
> 
> Here's the code. I hope I don't misunderstand the whole concept. :-)
> 
> package MyApp::Controller::User
> 
> sub register {
>     my( $self, $c ) = @_;
> 
>     my $user_class = $c->model('DB::User'); # this unfortunately 
> returns  DBIx::Class::ResultSet

Not unfortunately; that's by design. If you want to add a register() 
method that creates an object, create a custom resultset class -

package My::User::ResultSet;

use base qw/DBIx::Class::ResultSet/;

sub register {
   ...
   $self->result_source->schema->txn_do(sub { ... $self->create({ ... 
});  ...});
}

and in the schema class,

__PACKAGE__->resultset_class('My::User::ResultSet');

>     my $user = $user_class->register(); # want to create an object
> 
> }

DBIx::Class doesn't use class methods to access the datastore, since 
class methods are effectively once-per-object tree and it allows for 
multiple connections via the same schema class in a single process.

Class methods are almost always a poor paradigm; Catalyst is now 
minimally dependent on them and when we do the application class / 
context class split we'll be rid of them pretty much entirely.



More information about the Catalyst mailing list