Painless Memcached Configuration With Catalyst & DBIx::Class

This tutorial will show you how to:

* Easily add resultset level caching to your Catalyst::Model::DBIC::Schema calls.
* Move your Catalyst::Plugin::Session into memcached.
* Have a convenient $ctx->cache method available for anything else you might want to cache.



* Cache::Memcached
* Cache::Memcached::GetParserXS

Catalyst Plugins:

* Catalyst::Plugin::ConfigLoader
* Catalyst::Plugin::Session
* Catalyst::Plugin::Cache
* Catalyst::Plugin::Session::Store::Cache


* DBIx::Class::Cursor::Cached

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. See the DBIx::Class::Cursor::Cached docs 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.


--Samuel Kaufman, <skaufman at>