The first step to really working with Catalyst is to venture out and write your own components. Whether it is a view or model they share the same common ancestor, which is Catalyst::Component. Catalyst::Component is an important part of Catalyst, as it sets up the model, view or controller object. Catalyst will handle instantiation (calling ->new) as well as calling a setup method called COMPONENT. While both of these methods can be overridden, it is better to override COMPONENT if you need to execute code at instantiation time.

Important Note: whatever object is returned from COMPONENT, Catalyst treats as the object for that model or view. This means that if you return a different object from an overridden COMPONENT method, that is what you will get back from calling $c->model("Foo");.

More on that further down, for now a very simple model class that has default configuration:

package MyApp::Model::Foo;

use warnings;
use strict;

# You must inherit from Catalyst::Model, which in turn inherits from Catalyst::Component
use base qw/Catalyst::Model Catalyst::Accessor::Fast/;

# Make an accessor for 'foo'.  Inheriting from Catalyst::Accessor::Fast lets us easily do that
__PACKAGE__->mk_accessors('foo');

# All Catalyst components have ->config available to them.  This is merged in with the application-level
# configuration after instantiation.
__PACKAGE__->config(
   'foo' => 'default foo value'
);

1;

That's it, that is all that is there for your model to exist. Catalyst (and friends) handle everything else. If you want to get at the 'foo' variable, you simply have to use the accessor:

$c->model("Foo")->foo; # returns 'default foo value';
$c->model("Foo")->foo('new value');

It's important to remember that while Catalyst does some abstraction of the mundane code, it is still just perl. That means that if you add a method to the Foo model above, it will be available via $c->model("Foo"), which as discussed above, is simply an instantiation of MyApp::Model::Foo.

So, to change this, override the COMPONENT method:

package MyApp::Model::Foo;

use base 'Catalyst::Model';

use External::Module;

sub COMPONENT {
    my ( $self ) = @_;
    return External::Module->new;
}

Now, all calls to $c->model("Foo") return the instant of External::Module. Use this wisely, and also sparingly. If you find yourself binding to external modules, it is highly recommended to use Catalyst::Model::Adaptor to do it, rather than writing the code yourself.

My tags:
 
Popular tags:
 
Powered by Catalyst
Powered by MojoMojo Hosted by Shadowcat - Managed by Nordaaker