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
11 Catalyst::Model::DBIC::Schema
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 =head1 CONFIG PARAMETERS
48 Turn caching on or off, you can use:
50 $c->model('DB')->caching(0);
52 to disable caching at runtime.
56 has 'caching' => (is => 'rw', isa => 'Int', default => 1);
61 return if defined $self->caching && !$self->caching;
65 if (my $cursor_class = $self->connect_info->{cursor_class}) {
66 unless ($cursor_class->can('clear_cache')) {
67 carp "Caching disabled, cursor_class $cursor_class does not"
72 my $cursor_class = 'DBIx::Class::Cursor::Cached';
74 unless (eval { Class::MOP::load_class($cursor_class) }) {
75 carp "Caching disabled, cannot load $cursor_class: $@";
79 $self->connect_info->{cursor_class} = $cursor_class;
85 before ACCEPT_CONTEXT => sub {
91 unless ($c->can('cache') && ref $c->cache) {
92 $c->log->warn("DBIx::Class cursor caching disabled, you don't seem to"
93 . " have a working Cache plugin.");
95 $self->_reset_cursor_class;
99 if (ref $self->schema->default_resultset_attributes) {
100 $self->schema->default_resultset_attributes->{cache_object} =
103 $self->schema->default_resultset_attributes({
104 cache_object => $c->cache
111 =head2 _reset_cursor_class
113 Reset the cursor class to L<DBIx::Class::Storage::DBI::Cursor> if it's set to
114 L<DBIx::Class::Cursor::Cached>, if possible.
118 sub _reset_cursor_class {
121 if ($self->connect_info->{cursor_class} eq 'DBIx::Class::Cursor::Cached') {
122 $self->storage->cursor_class('DBIx::Class::Storage::DBI::Cursor')
123 if $self->storage->can('cursor_class');
131 L<Catalyst::Model::DBIC::Schema>, L<DBIx::Class>, L<Catalyst::Plugin::Cache>,
132 L<Cache::FastMmap>, L<DBIx::Class::Cursor::Cached>
136 Rafael Kitover, C<rkitover@cpan.org>
140 This program is free software, you can redistribute it and/or modify it
141 under the same terms as Perl itself.