Painless Memcached Configuration With Catalyst & DBIx::Class
- 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.
Memcached: Catalyst Plugins:
- Catalyst::Plugin::ConfigLoader
- Catalyst::Plugin::Session
- Catalyst::Plugin::Cache
- Catalyst::Plugin::Session::Store::Cache
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 MyApp.pm 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/ ConfigLoader Session Cache Session::Store::Cache /;
Now, configure Catalyst::Plugin::Cache. Here's an example for etc/myapp_local.pl:
#!/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:
<Model::MyAppDB> schema_class MyApp::Schema <connect_info> (your connect_info) cursor_class DBIx::Class::Cursor::Cached traits Caching </connect_info> </Model::MyAppDB>
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 http://lists.scsys.co.uk/pipermail/catalyst/2010-November/026159.html
Oh cool, thanks for the heads up!