Because Perl definitely isn't dead.
Random header image... Refresh for more!

Using your own modules as Catalyst Models

So you want to write a funky new model for Catalyst you say. Well the easy way to start would be to use the helper script to create a nice new model and start adding functionality. Woah there! One minute. If you continue down this route then a year down the line when it’s time to reimplement your site you are stuck with Catalyst. Or what if you need to write another app that uses your model.

So how do we get round this? We write a standard Perl module. Forget Catalyst for the time being, and of course write it like it’s meant for CPAN. Develop your module and use a test suite to test it as you go. No point waiting for Catalyst to restart every time you want to test a change and get the advantage that your tests will still hold true when you come back to this code in 6 months.

Eventually you will get to the point when your module is ready to be plugged into Catalyst. Now it’s time to create a model. Run the helper script as you would normally to do this. Now comes the interesting part…. As Catalyst instantiates all the models at initialisation time we still need to initialise our module so we use the COMPONENT method. We create a COMPONENT method within our model that initialises an instance of the module we created.

Something like:

use MyModule;
sub COMPONENT {
    my ($self, $c, @config) = @_;
    return MyModule->new(@config);
}

So now we have an instance of our model to work with. The config can be set from the Catalyst config by setting

$c->config->{'Model'}->{'MyModule'} = [<SOME CONFIG>];

The COMPONENT method is called when the Catalyst app is initialised and so it’s only called once per instance. If you want to initialise your module on a per request basis add a retrieve method to return a new instance of your module.

0 comments

There are no comments yet...

Kick things off by filling out the form below.

Leave a Comment