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.
DEPENDENCIES
Memcached:
Catalyst Plugins:
- * Catalyst::Plugin::ConfigLoader
- * Catalyst::Plugin::Session
- * Catalyst::Plugin::Cache
- * Catalyst::Plugin::Session::Store::Cache
DBIx::Class:
So dump all those in your Makefile.PL and you're halfway there.
CONFIGURATION
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).
EXAMPLES
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.
AUTHOR
--Samuel Kaufman, <skaufman at cpan.org>
- Previous
- Next