1 package Catalyst::Model::DBIC::Schema::Role::Caching;
4 use Carp::Clan '^Catalyst::Model::DBIC::Schema';
6 use namespace::clean -except => 'meta';
10 Catalyst::Model::DBIC::Schema::Role::Caching - Query caching support for
22 $c->model('DB::Table')->search({ foo => 'bar' }, { cache_for => 18000 });
26 Enable caching support using L<DBIx::Class::Cursor::Cached> and
27 L<Catalyst::Plugin::Cache>.
29 In order for this to work, L<Catalyst::Plugin::Cache> must be configured and
30 loaded. A possible configuration would look like this:
39 Then in your queries, set the C<cache_for> ResultSet attribute to the number of
40 seconds you want the query results to be cached for, eg.:
42 $c->model('DB::Table')->search({ foo => 'bar' }, { cache_for => 18000 });
44 =bead1 CONFIG PARAMETERS
50 Turn caching on or off, you can use:
52 $c->model('DB')->caching(0);
54 to disable caching at runtime.
60 has 'caching' => (is => 'rw', isa => 'Int', default => 1);
65 return if defined $self->caching && !$self->caching;
69 if (my $cursor_class = $self->connect_info->{cursor_class}) {
70 unless ($cursor_class->can('clear_cache')) {
71 carp "Caching disabled, cursor_class $cursor_class does not"
76 my $cursor_class = 'DBIx::Class::Cursor::Cached';
78 unless (eval { Class::MOP::load_class($cursor_class) }) {
79 carp "Caching disabled, cannot load $cursor_class: $@";
83 $self->connect_info->{cursor_class} = $cursor_class;
89 before ACCEPT_CONTEXT => sub {
95 unless ($c->can('cache') && ref $c->cache) {
96 $c->log->warn("DBIx::Class cursor caching disabled, you don't seem to"
97 . " have a working Cache plugin.");
99 $self->_reset_cursor_class;
103 if (ref $self->schema->default_resultset_attributes) {
104 $self->schema->default_resultset_attributes->{cache_object} =
107 $self->schema->default_resultset_attributes({
108 cache_object => $c->cache
117 =item _reset_cursor_class
119 Reset the cursor class to L<DBIx::Class::Storage::DBI::Cursor> if it's set to
120 L<DBIx::Class::Cursor::Cached>.
124 sub _reset_cursor_class {
127 if ($self->connect_info->{cursor_class} eq 'DBIx::Class::Cursor::Cached') {
128 $self->storage->cursor_class('DBIx::Class::Storage::DBI::Cursor');
138 L<Catalyst::Model::DBIC::Schema>, L<DBIx::Class>, L<Catalyst::Plugin::Cache>,
139 L<Cache::FastMmap>, L<DBIx::Class::Cursor::Cached>
143 Rafael Kitover, C<rkitover@cpan.org>
147 This program is free software, you can redistribute it and/or modify it
148 under the same terms as Perl itself.