1 package DBIx::Class::Cursor::Cached;
11 my ($storage, $args, $attrs) = @_;
12 $class = ref $class if ref $class;
13 # This gives us the class the storage object -would- have used
14 # (since cursor_class is inherited Class::Accessor::Grouped type)
15 my $inner_class = (ref $storage)->cursor_class;
16 my $inner = $inner_class->new(@_);
17 if ($attrs->{cache_for}) {
20 cache_for => delete $attrs->{cache_for},
21 cache_object => delete $attrs->{cache_object},
22 # this must be here to ensure the deletes have happened
23 cache_key => $class->_build_cache_key(@_),
26 return bless(\%args, $class);
28 return $inner; # return object that -would- have been constructed.
33 return @{($self->{data} ||= $self->_fill_data)->{$self->{pos}++}||[]};
38 return @{$self->{data} ||= $self->_fill_data};
45 sub _build_cache_key {
46 my ($class, $storage, $args, $attrs) = @_;
47 return Digest::SHA1::sha1_hex(Storable::nfreeze([ $args, $attrs ]));
52 my $cache = $self->{cache_object};
53 my $key = $self->{cache_key};
54 return $cache->get($key) || do {
55 my $data = [ $self->{inner}->all ];
56 $cache->set($key, $data, $self->{cache_for});
63 $self->{cache_object}->remove($self->{cache_key});
71 DBIx::Class::Cursor::Cached - cursor class with built-in caching support
75 my $schema = SchemaClass->connect(
76 $dsn, $user, $pass, { cursor_class => 'DBIx::Class::Cursor::Cached' }
79 $schema->default_resultset_attributes({
80 cache_object => Cache::FileCache->new({ namespace => 'SchemaClass' }),
83 my $rs = $schema->resultset('CD')->search(undef, { cache_for => 300 });
85 my @cds = $rs->all; # fills cache
87 $rs = $schema->resultset('CD')->search(undef, { cache_for => 300 });
90 @cds = $rs->all; # uses cache, no SQL run
92 $rs->cursor->clear_cache; # deletes data from cache
94 @cds = $rs->all; # refills cache
98 Matt S Trout <mst@shadowcat.co.uk> http://www.shadowcat.co.uk/
100 Initial development sponsored by and (c) Takkle, Inc. 2007
104 This library is free software under the same license as perl itself