Questions from the QueryLog: access catalyst config from a model

Published · Saturday, 8 August 2009 (Updated · 7 March 2010)

Refer to the documentation for Catalyst::Component as you go through this.

First you need to set the configuration. You can put anything into the model’s configuration via any of the regular routes–

In the config file(s), e.g.: myapp…


    - list
    - of
    - arguments
  key: value


    args   list
    args   of
    args   arguments
    key   value


  <Model::SomeModel key="value">



In the application

package MyApp;
# Many lines snipped…
  "Model::SomeModel" => { args => ["list", "of", "arguments"],
                          key => "value" },

In the model itself

package MyApp::Model::SomeModel;
# Many lines snipped…
__PACKAGE__->config(args => ["list", "of", "arguments"],
                    key => "value");

That puts the information into the model object directly and its config. And then access is available directly from the object or indirectly from its config method. E.g., within subs/methods of your model class you can see–

$self->{args}->[1] eq 'of'
$self->{args}->[1] eq $self->config->{args}->[1]

You can also add methods to your model so that getting the data is less susceptible to typos; e.g., $self->{arg}->[1]. The following will give you a read only (ro) args method to an array reference of strings and not just an {args} hash reference.

package MyApp::Model::SomeModel;
use parent "Catalyst::Model";
use Moose;

has "args" => 
    is => "ro",
    isa => "ArrayRef[Str]"
    default => sub {[]};



Then your $self->args works; as a getter only because we specified it read only. And within a controller that could look like

for my $arg ( @{ $c->model("SomeModel")->args } )
    # Do something with the argument.

digg stumbleupon reddit Fark Technorati Faves

« 10 Catalyst models in 10 days1 · Questions from the QueryLog: catalyst model open text file »
« Perl resources, modules, and sample code »