Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Catalyst Models Definitive Guide

by ait (Hermit)
on Jul 20, 2011 at 13:56 UTC ( #915657=perltutorial: print w/replies, xml ) Need Help??

Updates and Errata

Update July 28th 2011

The initial release of the code had a possible bug related to the order that the Catalyst instances get loaded. The risk being that the HomeGrownModel glue class could load before the DBIx::Class one. The new version delays the initialization of the HomeGrownModel class instance, until after the application has fully loaded by means of using the Moose after feature on the Catalyst method setup_components. The code explanations below were adjusted to reflect this.

Update August 2nd 2011

There was still a bug on modelthree that needed fixing. That's what happens when you don't write tests, so I will be creating these tests soon.


A lot of information is available about models, both in the Catalyst POD, books, this Wiki and the many discussion on the topic in mailing lists forums and IRC. Everywhere you read you will find comments like "make your controllers thin", "keep your model independent from Catalyst", "the model is just a thin layer", etc. but none of them actually tell you HOW to do it.

This guide was developed with actual code to help you understand quickly and easily the different "Model" options you have at your hands when developing with Catalyst. in the best Perl tradition, TMTOWTDI so you are invited to continue your study after going through this guide.

The idea behind the "Model"

By now you should have a pretty good idea of the MVC design pattern, so to correctly separate the concerns, your business logic should be written as generic re-usable code that is independent from Catalyst itself. So the first distinction we must make is the difference between YOUR Model and the Catalyst Model Layer. Like everyone agrees: your model should be implementation-independent code that can be re-used, and hopefully published on the CPAN for anyone to use, with or without Catalyst, and the Catalyst Model should be a thin wrapper that connects your model with the catalyst M layer.

The biggest confusion comes from the fact that both in Catalyst and almost every other MVC Web development framework, the M layer is analogous to the ORM (DBIx::Class in Catalyst's case).

This makes some sense because after all, in many Web applications, the M code is very much CRUD with some simple logic. But models can, and should be much more than that...

Three Patterns for M

In the scope of this guide we will explore three ways to implement your M layer and code your own Models.

Download the Sample Code

Before we continue, you must download the latest version of the code for this tutorial. You can check-out the latest version anonymously at:
  svn co svn://
This will download a very simple Catalyst application that demonstrates the three model options described in this guide.

M Pattern #1: Using the DBIC Model Directly

What you learn from tutorials and books is usually that the M layer is in fact the ORM, and in many cases it is, as many Web-based applications are mostly Forms and CRUD. But once you start adding a little bit of logic, your controller code will get messy really fast. You could of course, factorize code as private methods in the controller (or Action Classes, etc.) but this would be cumbersome and worthless for re-use by other controllers, and of course, impossible to use outside of Catalyst. But, since this is the most common "Model", let's explore this first pattern in order to understand it's limitations. In the sample code you can see that we use the ORM directly as the M layer like so (in the class Models::Controller::modelone):
sub index :Path :Args(0) { my ( $self, $c ) = @_; my @people = $c->model('Models::People')->all(); $c->stash->{people} = \@people; }
Pretty straight forward, except that it's very deceiving for the inadvertent coder. Many people don't realize that the line:
is actually a shortcut for this:
Remember that "Models" is the name of the Catalyst application developed for this guide.

Disadvantages of M Pattern #1

The main disadvantage of this first approach to M is that the only methods in the actual model itself are the query and CRUD methods of the ORM. Everything else must be coded in the controller or in libraries loaded directly on the controller, which somewhat violates the principles of separation of concerns of the MVC pattern in the first place. By now I hope you are beginning to understand that your DBIC Schema is just one particular Model and that you can have more than one model in a Catalyst application. It can be another DBIC model (actually a DBIC Schema), an extension of the schema, or it can be a completely homegrown one.

M Pattern #2: Extending the DBIC Model

This second pattern allows for you to extend the Schema files in order to add your own methods, so instead of calling the ORM methods directly, you can wrap them in the business logic, which is hidden neatly away in the Schema extension classes. The mechanism for doing this is described in the "Create a ResultSet Class" section of the Catalyst::Manual::Tutorial::04_BasicCRUD POD. From the controller perspective the approach isolates your controller code completely by calling more intelligent methods. In this case it's just a simple wrapper to the previous example, but it illustrates the point: In Models::Controller::modeltwo you will find the index method to be:
sub index :Path :Args(0) { my ( $self, $c ) = @_; $c->stash->{people} = $c->model('Models::People')->listall(); }

Here the extended method "listall" hides away any complexity inside the extended class which is simply a common DBIC overlay class like so:

package Models::Schema::ModelsDB::ResultSet::People; use strict; use warnings; use base 'DBIx::Class::ResultSet'; sub listall { my $self = shift; my @people = $self->all(); return \@people; } 1;
For many applications this way of coding your models will be more than adequate, but only if the business code is closely related to the RDBMS model. In this pattern, you will probably hang your business method to the closest DBIC class and from there you might wind up using other DBIC classes (i.e. a method in one class that updates several tables). To accomplish this you will need a handle to the DBIC schema itself and the next pattern will show you how.

M Pattern #3: Homegrown Model

The third and final M pattern in this guide is a more generic approach which will allow you to craft your code completely independent from Catalyst and then connect it to Catalyst using a Catalyst Model Wrapper. It's also very probable that your homegrown model classes will need access to the DBIC Schema and we will also show you how to do that. From the controller (Models::Controller::modelthree) your homegrown model works much like the DBIC model in the first and second examples above:
sub index :Path :Args(0) { my ( $self, $c ) = @_; $c->stash->{people} = $c->model('HomeGrownModel')->homegrown_peop +le(); }
This example demonstrates two things. Firstly, is the Catalyst Model wrapper which acts as an interface between your homegrown independent Perl class and the Catalyst framework:
package Models::Model::HomeGrownModel; use base 'Catalyst::Model'; use HomeGrown; use Moose; our $AUTOLOAD; has 'HomeGrownInstance' => ( is => 'rw', isa => 'HomeGrown', ); # Gotcha: using the COMPONENT method like shown below may get you in # trouble because your component mat very well be loaded before the # DBIC model does. The initialize_after_setup hack shown further down, # is a work-around to deferr the instatiation of things, or at least # making sure that your model initializes lastly. #sub COMPONENT { # my ( $self, $app ) = @_; # my $dbic_schema = $app->model('ModelsDB')->schema; # return HomeGrown->new( schema => $dbic_schema ); #} sub initialize_after_setup { my ( $self, $app ) = @_; $app->log->debug('Initializing Homegrown with schema AFTER app is fu +lly loaded...'); $self->HomeGrownInstance( HomeGrown->new( schema => $app->model('ModelsDB')->schema ) ); } # Here you would map your Catalyst Model methods to the actual model # in this example we will just forward everything as is to our # HomeGrown external Model sub AUTOLOAD { my $self = shift; my $name = $AUTOLOAD; $name =~ s/.*://; $self->HomeGrownInstance->$name(@_); } 1;

As you can see this is just a very thin wrapper around your homegrown class. We also demonstrate a correct way (YMMV) of passing the instantiated DBIC schema to your homegrown external class so you can access the database from there whilst taking advantage of all the connection and re-connection magic of DBIC which is already set-up and working for you thanks to Catalyst.

Finally, for this to work correctly, your model class should be instantiated lastly by Catalyst. This bit of Moose after magic in the main application class ( will do the trick. This code must be placed before the application configuration setup sections, preferably right after the $VERSION declarations. See actual sample code for details.

after 'setup_components' => sub { my $app = shift; for (keys %{ $app->components }) { $app->components->{$_}->initialize_after_setup($app) if $app->components->{$_}->can('initialize_after_setup'); } };

How this hack works: The after feature of this Moose declaration will call the inline sub after the setup_components sub of the main application class has been called, that is, after all other components have been set up. The loop in this sample sub will go through every loaded component and identify those that have the initialize_after_setup method and call it if it exists.

Your Model class would look something like this:

package HomeGrown; use Moose; use namespace::autoclean; has 'schema' => ( is => 'rw', required => 1, isa => 'DBIx::Class::Schema', ); sub homegrown_people { my $self = shift; my @people = $self->schema->resultset('People')->all(); return \@people; } 1;
Notice how your model (or more precisely your business logic implementation) class is completely independent from Catalyst and can be used for any purpose. In our example above, it still depends on a specific database schema and of course DBIC but it's just for illustration of the concept. another approach could be to do the DBIC stuff in the Catalyst model layer (the thin layer above) and only pass specific data to the actual implementation class, this way keeping the latter independent even from that particular database model. As always TMTOWTDI and your mileage may vary, but hopefully this guide has served you as an opening these possibilities and variants on the same idea: keep your logic code in the M layer and the Catalyst M layer should be as thin as possible.

Things to avoid at all cost

As almost every single document about Catalyst will tell you, the worst thing you could do is make your Model dependent of the context of the HTTP request. In other words, passing $c from the controller to your model, because "it's pretty brain dead". If for any reason you do in fact need information from the context there is a method called ACCEPT_CONTEXT but stay away from that unless you really justify it. And this is just scratching the surface. For most applications though, it will be more than enough to work within the guidelines of M Pattern #3 above

See Also

For more information about Context-dependent models please refer to:

Links to similar Tutorials

Replies are listed 'Best First'.
Re: Catalyst Models Definitive Guide
by mkchris (Sexton) on Jan 20, 2022 at 11:27 UTC
    Hello - I appreciate this is now a very old post - I'm trying to download the sample code, as I have got as far as modelone and modeltwo on my own, but I think modelthree could be useful to me - it looks like the SVN repository is no longer up, which again is probably not surprising given the age of the post - is there anywhere else that it's available please, so I can have a look and try and understand?

    Many thanks in advance.

      Looks like you can just cut and paste the code if you follow the accompanying instructions to set things up. You might get a reply from the author though for an alternative repository.

      Feel free to take a stab at it and come back with questions if it’s not working.

      Sidenote: I would recommend against–

      use base 'DBIx::Class::ResultSet'; sub listall { my $self = shift; my @people = $self->all(); return \@people; }

      Well-behaved resultsets should only return the same because they are expected to be chainable and ->all is kind of weirdly redundant so might lead to misunderstandings or over-elaboration of what could be more simple code.

        Thank you, yes I have generally avoided doing ->all in a resultset method for the same reason; also because I may want to return a resultset rather than an array, so if I want an array I can either call it in array context: @people = $c->model("DB::People")->listall or chain $c->model("DB::People")->listall->all.
      is there anywhere else that it's available please

      If all else fails, I suggest sending a message to ait via the Chatterbox.
      I see that he signed in 6 days ago, so it would seem that he is still keeping an eye on events at the monastery.
      (It's quite likely that he won't even see the post you've just made - but there's a reasonable chance he'll notice an /msg sent directly and specifically to him.)

        Ah thank you for that, I will ask directly!
        Oh thank you very much, I'll take a look!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perltutorial [id://915657]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2022-08-18 17:24 GMT
Find Nodes?
    Voting Booth?

    No recent polls found