1 package DBIx::Class::Cursor::Cached;
11 $VERSION = '0.999001_01';
15 my ($storage, $args, $attrs) = @_;
16 $class = ref $class if ref $class;
17 # This gives us the class the storage object -would- have used
18 # (since cursor_class is inherited Class::Accessor::Grouped type)
19 my $inner_class = (ref $storage)->cursor_class;
20 my $inner = $inner_class->new(@_);
21 if ($attrs->{cache_for}) {
24 cache_for => delete $attrs->{cache_for},
25 cache_object => delete $attrs->{cache_object},
26 # this must be here to ensure the deletes have happened
27 cache_key => $class->_build_cache_key(@_),
30 return bless(\%args, $class);
32 return $inner; # return object that -would- have been constructed.
37 return @{($self->{data} ||= $self->_fill_data)->{$self->{pos}++}||[]};
42 return @{$self->{data} ||= $self->_fill_data};
49 sub _build_cache_key {
50 my ($class, $storage, $args, $attrs) = @_;
51 return Digest::SHA1::sha1_hex(Storable::nfreeze([ $args, $attrs ]));
56 my $cache = $self->{cache_object};
57 my $key = $self->{cache_key};
58 return $cache->get($key) || do {
59 my $data = [ $self->{inner}->all ];
60 $cache->set($key, $data, $self->{cache_for});
67 $self->{cache_object}->remove($self->{cache_key});
71 sub cache_key { shift->{cache_key} }
77 DBIx::Class::Cursor::Cached - cursor class with built-in caching support
81 my $schema = SchemaClass->connect(
82 $dsn, $user, $pass, { cursor_class => 'DBIx::Class::Cursor::Cached' }
85 $schema->default_resultset_attributes({
86 cache_object => Cache::FileCache->new({ namespace => 'SchemaClass' }),
89 my $rs = $schema->resultset('CD')->search(undef, { cache_for => 300 });
91 my @cds = $rs->all; # fills cache
93 $rs = $schema->resultset('CD')->search(undef, { cache_for => 300 });
96 @cds = $rs->all; # uses cache, no SQL run
98 $rs->cursor->clear_cache; # deletes data from cache
100 @cds = $rs->all; # refills cache
104 Matt S Trout <mst@shadowcat.co.uk> http://www.shadowcat.co.uk/
106 Initial development sponsored by and (c) Takkle, Inc. 2007
110 This library is free software under the same license as perl itself