Bug 26922: Regression tests
[koha.git] / Koha / Template / Plugin / Cache.pm
blob93bbf0f24dfd0574e677019c2e05aa23c61b99e4
1 package Koha::Template::Plugin::Cache;
3 # Copyright Catalyst IT 2011
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use strict;
21 use warnings;
22 use base qw( Template::Plugin );
23 use Template::Plugin;
24 use C4::Context;
26 #------------------------------------------------------------------------
27 # new(\%options)
28 #------------------------------------------------------------------------
30 sub new {
31 my ( $class, $context, $params ) = @_;
32 my $cache;
33 if ( $params->{cache} ) {
34 $cache = delete $params->{cache};
36 else {
37 require Koha::Cache;
38 $cache = Koha::Caches->get_instance();
40 my $self = bless {
41 CACHE => $cache,
42 CONFIG => $params,
43 CONTEXT => $context,
44 }, $class;
45 return $self;
48 #------------------------------------------------------------------------
49 # $cache->include({
50 # template => 'foo.html',
51 # keys => {'user.name', user.name},
52 # ttl => 60, #seconds
53 # });
54 #------------------------------------------------------------------------
56 sub inc {
57 my ( $self, $params ) = @_;
58 $self->_cached_action( 'include', $params );
61 sub proc {
62 my ( $self, $params ) = @_;
63 $self->_cached_action( 'process', $params );
66 sub _cached_action {
67 my ( $self, $action, $params ) = @_;
68 my $key;
69 if ( $params->{key} ) {
70 $key = delete $params->{key};
72 else {
73 my $cache_keys = $params->{keys};
74 $key = join(
75 ':',
77 $params->{template},
78 map { "$_=$cache_keys->{$_}" } keys %{$cache_keys}
82 my $result = $self->{CACHE}->get_from_cache($key);
83 if ( !$result ) {
84 $result = $self->{CONTEXT}->$action( $params->{template} );
85 $self->{CACHE}
86 ->set_in_cache( $key, $result, { expiry => $params->{ttl} } );
88 return $result;
93 =head1 NAME
95 Koha::Template::Plugin::Cache - cache output of templates
97 =head1 SYNOPSIS
99 [% USE cache = Cache %]
102 [% cache.inc(
103 'template' => 'slow.html',
104 'keys' => {'user.name' => user.name},
105 'ttl' => 360
106 ) %]
108 # or with a pre-defined Cache::* object and key
110 [% USE cache = Cache( cache => mycache ) %]
112 [% cache.inc(
113 'template' => 'slow.html',
114 'key' => mykey,
115 'ttl' => 360
116 ) %]
118 __END__