Using Config Files In Catalyst

I’ve been doing quite a bit of work with the Catalyst MVC framework lately.

Moving from development to live, the config system has really shown it’s usefulness. Instead of hardcoding values, we can simply move them out to the site’s config file and access these value programatically. It means we can run the same codebase on multiple machines and just tweak the config to pick up things like different database connection strings, cache settings etc.

I like to have my config file in Config::General format as it’s similar to Apache’s config files, but Catalyst can also handle config files in INI, JSON, Perl, XML or YAML, so you can use whatever you are most comfortable with.

Let’s have a look at a few examples. We’ll assume the Catalyst Application is called MyApp. This means we’ll have a perl module in our lib directory called MyApp.pm, and a config file called myapp.conf in the root directory.

MyApp.pm contains all the default values, but you can override these with myapp.conf. myapp.conf always takes priority.

Let’s create a simple string to say where our application is running. In MyApp.pm, in the __PACKAGE__->config we add an entry to the hash like this…


servername => 'dev',

Now when we run our application, we can access this value using the following code…


$c->config->{servername};

This will return “dev”. We can override this in the conf file, so in myapp.conf we can add…


servername production

Now when we run our application code, we’ll see “production” instead of “dev”.

A more practical use of the config file is to move out the database connection details. Let’s assume we have a simple MySQL based model in our lib/Model directory called Model::MyApp that handles our database work. We can override database connection details stored here in myapp.conf using something like this…

<"Model::MyApp">
connect_info dbi:mysql:myapp
connect_info www-rw
connect_info password
<connect_info>
AutoCommit 1
</connect_info>
</"Model::MyApp">

Now when we run the application, the connection details we entered in our conf file will be used instead. This is very useful as it means we don’t have to alter our codebase when we move the application to different servers that may have different databases. It’s also good for keeping dev, staging and live seperate as all that’s needed is a change to one config file.

For more information on how Catalyst can use a config file, have a look at
Catalyst::Plugin::ConfigLoader.