38. package ModPerl::WordPress::CacheManager;
# e.g.
# # in VirtualHost block directive
# PerlMapToStorageHandler ModPerl::WordPress::CacheManager
use strict;
use warnings;
use Apache2::RequestRec ();
use Apache2::Const -compile => qw(OK DECLINED);
sub handler {
my $r = shift; # request object
# $r->uri() $filename
# $r->filename($filename)
...
return Apache2::Const::DECLINED;
}
1;
39. package ModPerl::WordPress::CacheManager;
use strict;
use warnings;
use Apache2::RequestRec ();
use Apache2::RequestUtil (); # for pnotes method
use Apache2::Const -compile => qw(OK DECLINED);
use APR::Table (); # for notes method
use File::Basename qw(dirname);
use File::Path qw(make_path);
use constant CACHE_LIFETIME => 3600;
sub handler {
my $r = shift;
if ( !is_cache_enable($r) ) {
return Apache2::Const::DECLINED;
}
manage_cache($r);
return Apache2::Const::DECLINED;
}
40. package ModPerl::WordPress::CacheManager;
# (snip)
sub is_cache_enable {
my $r = shift;
return $r->uri eq '/index.php'; # WordPress /index.php (entry-point)
}
sub manage_cache {
my $r = shift;
my $cache_filename = guess_cache_filename($r);
$r->notes->set( mpwp_cache_filename => $cache_filename );
if ( !-f $cache_filename
|| time - (stat _)[9] > CACHE_LIFETIME ) { # 9=mtime
$r->pnotes( mpwp_cache_generate_cb => &mpwp_cache_filename );
# ...
make_path(dirname($cache_filename));
} else {
$r->handler('default-handler');
$r->filename($cache_filename);
}
}
41. package ModPerl::WordPress::CacheManager;
# (snip)
sub mpwp_cache_filename {
my $f = shift;
my $contents_ref = shift; die if ref $contents_ref ne 'SCALAR';
my $filter_phase = !$f->ctx ? "INITIAL"
: $f->seen_eos ? "SEEN_EOS" : "IN_PROGRESS";
my $cache_filename = $f->r->notes->get("mpwp_cache_filename");
if ( $filter_phase eq "INITIAL" ) {
unlink $cache_filename; # remove old cache
}
if ( open my $fh, '>>', "$cache_filename.$$" ) {
print {$fh} $$contents_ref;
}
if ( $filter_phase eq "SEEN_EOS" ) {
rename "$cache_filename.$$" => $cache_filename;
}
}