399c6088caac3f8fc53a5c2aa8e410868a324792
[catagits/Web-Session.git] / lib / Plack / Session / Store / Cache.pm
1 package Plack::Session::Store::Cache;
2 use strict;
3 use warnings;
4
5 use Scalar::Util qw/blessed/;
6
7 use parent 'Plack::Session::Store';
8
9 use Plack::Util::Accessor qw[ cache ];
10
11 sub new {
12     my ($class, %params) = @_;
13
14     die('cache require get, set and remove method.')
15         unless blessed $params{cache}
16             && $params{cache}->can('get')
17             && $params{cache}->can('set')
18             && $params{cache}->can('remove');
19
20     bless { %params } => $class;
21 }
22
23 sub fetch {
24     my ($self, $session_id, $key) = @_;
25     my $cache = $self->cache->get($session_id);
26     return unless $cache;
27     return $cache->{ $key };
28 }
29
30 sub store {
31     my ($self, $session_id, $key, $data) = @_;
32     my $cache = $self->cache->get($session_id);
33     if ( !$cache ) {
34         $cache = {$key => $data};
35     }
36     else {
37         $cache->{$key} = $data;
38     }
39     $self->cache->set($session_id => $cache);
40 }
41
42 sub delete {
43     my ($self, $session_id, $key) = @_;
44     my $cache = $self->cache->get($session_id);
45     return unless exists $cache->{$key};
46
47     delete $cache->{ $key };
48     $self->cache->set($session_id => $cache);
49 }
50
51 sub cleanup {
52     my ($self, $session_id) = @_;
53     $self->cache->remove($session_id);
54 }
55
56 1;
57
58 __END__
59
60 =pod
61
62 =head1 NAME
63
64 Plack::Session::Store::Cache - Cache session store
65
66 =head1 SYNOPSIS
67
68   use Plack::Builder;
69   use Plack::Session::Store::Cache;
70   use CHI;
71
72   my $app = sub {
73       return [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello Foo' ] ];
74   };
75
76   builder {
77       enable 'Session',
78           store => Plack::Session::Store::Cache->new(
79               cache => CHI->new(driver => 'FastMmap')
80           );
81       $app;
82   };
83
84 =head1 DESCRIPTION
85
86 This will persist session data using the L<Cache> module. This
87 offers a lot of flexibility due to the many excellent L<CHI>
88 drivers available.
89
90 This is a subclass of L<Plack::Session::Store> and implements
91 it's full interface.
92
93 =head1 METHODS
94
95 =over 4
96
97 =item B<new ( %params )>
98
99 The constructor expects an the I<cache> param to be an
100 instance have get, set, and remove method, it will throw an exception
101 if that is not the case.
102
103 =item B<cache>
104
105 =back
106
107 =head1 BUGS
108
109 All complex software has bugs lurking in it, and this module is no
110 exception. If you find a bug please either email me, or add the bug
111 to cpan-RT.
112
113 =head1 AUTHOR
114
115 Masahiro Chiba
116
117 =cut