MooseX::WithCache - Easy Cache Access From Moose Objects
package MyObject; use Moose; use MooseX::WithCache; with 'MooseX::WithCache' => { backend => 'Cache::Memcached', ); no Moose; sub get_foo { my $self = shift; my $foo = $self->cache_get( 'foo' ); if ($foo) { $foo = $self->get_foo_from_database(); $self->cache_set(foo => $foo); } return $foo; } # main.pl my $object = MyObject->new( cache => Cache::Memcached->new({ ... }) ); my $foo = $object->get_foo(); # if you want to do something with the cache object, # you can access it via the name you gave in with staemtent # # with 'MooseX::WithCache' => { # name => 'cache', # default # .... # } my $cache = $object->cache;
MooseX::WithCache gives your object instant access to cache objects.
MooseX::WithCache s not a cache object, it just gives your convinient methods to access the cache through your objects.
By default, it gives you 3 methods:
cache_get($key) cache_set($key, $value, $expires) cache_del($key)
But if there's a backend provided for it, you may get extra methods tailored for that cache. For example, for Cache::Memcached, the backend provides these additional methods:
cache_get_multi(@keys); cache_incr($key); cache_decr($key);
Data extraction/injection to the cache can be disabled. Simply set the cache_disabled() attribute that gets installed
$object->cache_disabled(1); $object->cache_get($key); # won't even try
You can inspect what's going on with respect to the cache, if you specify MOOSEX_WITHCACHE_DEBUG=1 in the environment. This will caue MooseX::WithCache to display messages to STDERR.
Sometimes you want to give compound keys, or simply transform the cache keys somehow to normalize them.
MooseX::WithCache supports this through the cache_key_generator attribute. The cache_key_generator simply needs to be a MooseX::WithCache::KeyGenerator instance, which accepts whatever key provided, and returns a new key.
For example, if you want to provide complex key that is a perl structure, and use its MD5 as the key, you can use MooseX::WithCache::KeyGenerator::DumpChecksum to generate the keys.
Simply specify it in the constructor:
MyObject->new( cache => ..., cache_key_generator => MooseX::WithCache::KeyGenerator::DumpChecksum->new() );
Daisuke Maki <daisuke@endeworks.jp>
<daisuke@endeworks.jp>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See http://www.perl.com/perl/misc/Artistic.html
To install MooseX::WithCache, copy and paste the appropriate command in to your terminal.
cpanm
cpanm MooseX::WithCache
CPAN shell
perl -MCPAN -e shell install MooseX::WithCache
For more information on module installation, please visit the detailed CPAN module installation guide.