improved Store::File based on stuff in Store::CHI, ... added Store::Null and tests
[catagits/Web-Session.git] / lib / Plack / Session / Store / File.pm
1 package Plack::Session::Store::File;
2 use strict;
3 use warnings;
4
5 use Storable ();
6
7 use parent 'Plack::Session::Store';
8
9 use Plack::Util::Accessor qw[
10     dir
11     serializer
12     deserializer
13 ];
14
15 sub new {
16     my ($class, %params) = @_;
17
18     $params{'dir'} ||= '/tmp';
19
20     die "Storage directory (" . $params{'dir'} . ") is not writeable"
21         unless -w $params{'dir'};
22
23     $params{'serializer'}   ||= sub { Storable::nstore( @_ ) };
24     $params{'deserializer'} ||= sub { Storable::retrieve( @_ ) };
25
26     bless { %params } => $class;
27 }
28
29 sub fetch {
30     my ($self, $session_id, $key) = @_;
31     my $store = $self->_deserialize( $session_id );
32     return unless exists $store->{ $key };
33     return $store->{ $key };
34 }
35
36 sub store {
37     my ($self, $session_id, $key, $data) = @_;
38     my $store = $self->_deserialize( $session_id );
39     $store->{ $key } = $data;
40     $self->_serialize( $session_id, $store );
41 }
42
43 sub delete {
44     my ($self, $session_id, $key) = @_;
45     my $store = $self->_deserialize( $session_id );
46     return unless exists $store->{ $key };
47     delete $store->{ $key };
48     $self->_serialize( $session_id, $store );
49 }
50
51 sub cleanup {
52     my ($self, $session_id) = @_;
53     unlink $self->_get_session_file_path( $session_id );
54 }
55
56 sub _get_session_file_path {
57     my ($self, $session_id) = @_;
58     $self->dir . '/' . $session_id;
59 }
60
61 sub _serialize {
62     my ($self, $session_id, $value) = @_;
63     my $file_path = $self->_get_session_file_path( $session_id );
64     $self->serializer->( $value, $file_path );
65 }
66
67 sub _deserialize {
68     my ($self, $session_id) = @_;
69     my $file_path = $self->_get_session_file_path( $session_id );
70     $self->_serialize( $session_id, {} ) unless -f $file_path;
71     $self->deserializer->( $file_path );
72 }
73
74
75 1;
76
77 __END__
78
79 =pod
80
81 =head1 NAME
82
83 Plack::Session::Store::File - Basic file-based session store
84
85 =head1 DESCRIPTION
86
87 =head1 METHODS
88
89 =over 4
90
91 =item B<new ( %params )>
92
93 =item B<dir>
94
95 =item B<serializer>
96
97 =item B<deserializer>
98
99 =back
100
101 =head1 BUGS
102
103 All complex software has bugs lurking in it, and this module is no
104 exception. If you find a bug please either email me, or add the bug
105 to cpan-RT.
106
107 =head1 AUTHOR
108
109 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
110
111 =head1 COPYRIGHT AND LICENSE
112
113 Copyright 2009 Infinity Interactive, Inc.
114
115 L<http://www.iinteractive.com>
116
117 This library is free software; you can redistribute it and/or modify
118 it under the same terms as Perl itself.
119
120 =cut
121