| 1 | package Magpie::Plugin::Resource::Cache; | ||
| 2 | $Magpie::Plugin::Resource::Cache::VERSION = '1.141660'; | ||
| 3 | use Moose::Role; | ||
| 4 | |||
| 5 | # ABSTRACT: A Role to add Caching to a Resource; | ||
| 6 | # | ||
| 7 | use Magpie::Constants; | ||
| 8 | |||
| 9 | requires qw(mtime); | ||
| 10 | |||
| 11 | has cache => ( | ||
| 12 | is => 'ro', | ||
| 13 | lazy_build => 1, | ||
| 14 | ); | ||
| 15 | |||
| 16 | around 'GET' => sub { | ||
| 17 | my $orig = shift; | ||
| 18 | my $self = shift; | ||
| 19 | my $mtime = $self->mtime; | ||
| 20 | my $uri = $self->request->uri->as_string; | ||
| 21 | |||
| 22 | if ( $mtime && $mtime > 0 ) { | ||
| 23 | my $data = $self->cache->get($uri); | ||
| 24 | if ($data && defined $data->{resource} && defined defined $data->{resource}->{mtime} && $mtime == $data->{resource}->{mtime}) { | ||
| 25 | my $content = $data->{content}; | ||
| 26 | $self->data($content); | ||
| 27 | return DONE; | ||
| 28 | } | ||
| 29 | else { | ||
| 30 | # actual content will be added at the end of the pipeline process | ||
| 31 | my $data = { content => '', resource => { mtime => $mtime,}}; | ||
| 32 | $self->cache->set($uri, $data); | ||
| 33 | $self->parent_handler->add_handler('Magpie::Component::ContentCache'); | ||
| 34 | } | ||
| 35 | } | ||
| 36 | |||
| 37 | return $self->$orig(@_); | ||
| 38 | }; | ||
| 39 | |||
| 40 | after [qw(add_dependency delete_dependency)] => sub { | ||
| 41 | my $self = shift; | ||
| 42 | my $uri = $self->request->uri->as_string; | ||
| 43 | my $data = $self->cache->get($uri); | ||
| 44 | |||
| 45 | unless ( $data ) { | ||
| 46 | $data = {}; | ||
| 47 | } | ||
| 48 | |||
| 49 | $data->{resource}->{dependencies} = $self->dependencies; | ||
| 50 | |||
| 51 | $self->cache->set($uri, $data); | ||
| 52 | }; | ||
| 53 | |||
| 54 | 1; | ||
| 55 | |||
| 56 | __END__ | ||
| 57 | =pod | ||
| 58 | |||
| 59 | =head1 NAME | ||
| 60 | |||
| 61 | Magpie::Plugin::Resource::Cache - A Role to add Caching to a Resource; | ||
| 62 | |||
| 63 | =head1 VERSION | ||
| 64 | |||
| 65 | version 1.141660 | ||
| 66 | |||
| 67 | =head1 AUTHORS | ||
| 68 | |||
| 69 | =over 4 | ||
| 70 | |||
| 71 | =item * | ||
| 72 | |||
| 73 | Kip Hampton <kip.hampton@tamarou.com> | ||
| 74 | |||
| 75 | =item * | ||
| 76 | |||
| 77 | Chris Prather <chris.prather@tamarou.com> | ||
| 78 | |||
| 79 | =back | ||
| 80 | |||
| 81 | =head1 COPYRIGHT AND LICENSE | ||
| 82 | |||
| 83 | This software is copyright (c) 2011 by Tamarou, LLC. | ||
| 84 | |||
| 85 | This is free software; you can redistribute it and/or modify it under | ||
| 86 | the same terms as the Perl 5 programming language system itself. | ||
| 87 | |||
| 88 | =cut | ||
| 89 |