root/SearchResultsCache/trunk/plugins/SearchResultsCache/SearchResultsCache.pl

Revision 58, 2.3 kB (checked in by piroli, 9 ヶ月 ago)

MT3.15beta1に対応

Line 
1 package MT::Plugin::OMV::SearchResultsCache;
2 #   SearchResultsCache - Cache the searched results keyed to search queries in mt-search.cgi
3 #           Original Copyright (c) 2008 Piroli YUKARINOMIYA
4 #           Open MagicVox.net - http://www.magicvox.net/
5 #           @see http://www.magicvox.net/archive/2008/03082243/
6
7 use strict;
8 use Cache::File;
9 #use Data::Dumper;#DEBUG
10
11 # default expire time of cached content
12 use constant DEFAULT_EXPIRE =>          '7 days';
13
14 use vars qw( $MYNAME $VERSION );
15 $MYNAME = 'SearchResultsCache';
16 $VERSION = '1.1.0';
17
18 use base qw( MT::Plugin );
19 my $plugin = new MT::Plugin ({
20         name => $MYNAME,
21         version => $VERSION,
22         author_name => 'Piroli YUKARINOMIYA',
23         author_link => 'http://www.magicvox.net/',
24         doc_link => 'http://www.magicvox.net/archive/2008/03082243/',
25         description => <<HTMLHEREDOC,
26 Cache the searched results keyed to search queries in mt-search.cgi.
27 Cache-$Cache::VERSION is installed.
28 HTMLHEREDOC
29 });
30 MT->add_plugin( $plugin );
31
32 sub instance { $plugin }
33
34
35
36 ### Override searching method
37 require MT::App::Search;
38 no warnings qw( redefine );
39
40 my $sub_original = \&MT::App::Search::process;
41 *MT::App::Search::process = sub {
42     my( $app ) = @_;
43
44     ### Initialize cache component
45     my $cache = Cache::File->new(
46             cache_root => &get_cache_dir,
47             lock_level => Cache::File::LOCK_LOCAL(),
48             cache_depth => 2,
49     ) or $app->error( __PACKAGE__. ': Failed to initialize Cache::File class' );
50     ### Generate a cache-key from query string
51     my $q = $app->{query};
52     my $cache_key = join "\n", map { join ',', $_, $q->param( $_ ) } sort $q->param;
53     ### If cache hit, give the cached content and terminate here
54     if( defined( my $cached_content = $cache->get( $cache_key ))) {
55         return $cached_content;
56     }
57
58     ### Do searching with proper methods
59     my $content = $sub_original->( @_ ) or return;
60     # and store the retrieved content into cache component
61     $cache->set( $cache_key, $content, DEFAULT_EXPIRE );
62
63     $content;
64 };
65
66 ### Retrieve path that cache stored
67 sub get_cache_dir {
68     my $path = &instance->{full_path};
69     -d $path
70         ? "${path}/$MYNAME" # ex) /plugins/SearchResultsCache/SearchResultsCache
71         : "${path}.cache";  # ex) /plugins/SearchResultsCache.cache
72 }
73
74 1;
Note: See TracBrowser for help on using the browser.