Painless Memcached Configuration With Catalyst & DBIx::Class

This tutorial will show you how to: Dependencies:
Memcached: Catalyst Plugins: DBIx::Class:

So dump all those in your Makefile.PL and you're halfway there.

First we edit your Catalyst app's base package. Open up your version of and add:

    use Cache::Memcached::GetParserXS;
    use Cache::Memcached;

This will tell Cache::Memcached to use the XS Parser.

Now, in the section where you load your plugins, add the new ones in:

    use Catalyst qw/

Now, configure Catalyst::Plugin::Cache. Here's an example for etc/

    #!/usr/bin/env perl
    use strict;
    use warnings;
    return {
        'Plugin::Cache' => {
            backend => {
                namespace =>  'myapp:',
                class =>  'Cache::Memcached',
                servers => [ 'dev:11211' ]

Note, I didn't use a .pl config just for kicks. Notice how the 'servers' param takes an ArrayRef value. I tried and failed in expressing that in our Apache Conf style config, before realizing that ConfigLoader is just as happy to grab your .pl config alongside your regular config and merge them for you. Sometimes a cop-out is better than a hack.

Now we configure our model. In our apache style conf it would look like this:

        schema_class    MyApp::Schema
            (your connect_info)
            cursor_class DBIx::Class::Cursor::Cached
            traits Caching

Pat yourself on the back, you should be done (unless something went horribly wrong).

    my @sweet_loot = $ctx->model("MyAppDB::Loot")
      ->search({ sweet => 1 },{ cache_for => 300 })->all;

That $rs is now cached for 300 seconds. Look at DBIx::Class::Cursor::Cached for further explanation.

    my $cache = $ctx->cache;
    $cache->set('turtles',{ ilike => 'turtles' },600);
    my $do_i_like_turtles = $cache->get('turtles');

That's cached for 600 seconds. See Catalyst::Plugin::Cache for the docs.


There was a call for articles for a new Advent Calendar on the Catalyst mailing list. If you'd like to you could add this article to it.

More info at

Leave a comment

About Samuel Kaufman

user-pic CTO / Codemonkey,