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