f3bbe68bf380d649b5ea97b9ca3387fe7745970f
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Middleware / Stash.pm
1 use strict;
2 use warnings;
3
4 package Catalyst::Middleware::Stash;
5
6 use base 'Plack::Middleware';
7 use Exporter 'import';
8 use Carp 'croak';
9
10 our @EXPORT_OK = qw(stash get_stash);
11
12 sub PSGI_KEY { 'Catalyst.Stash.v1' };
13
14 sub get_stash {
15   my $env = shift;
16   return $env->{PSGI_KEY} ||
17     _init_stash_in($env);
18 }
19
20 sub stash {
21   my ($host, @args) = @_;
22   return get_stash($host->env)
23     ->(@args);
24 }
25
26 sub _create_stash {
27   my $stash = shift || +{};
28   return sub {
29     if(@_) {
30       my $new_stash = @_ > 1 ? {@_} : $_[0];
31       croak('stash takes a hash or hashref')
32         unless ref $new_stash;
33       foreach my $key (keys %$new_stash) {
34         $stash->{$key} = $new_stash->{$key};
35       }
36     }
37     $stash;
38   };
39 }
40
41 sub _init_stash_in {
42   my ($env) = @_;
43   return $env->{PSGI_KEY} ||=
44     _create_stash;
45 }
46
47 sub call {
48   my ($self, $env) = @_;
49   _init_stash_in($env);
50   return $self->app->($env);
51 }
52
53 =head1 TITLE
54
55 Catalyst::Middleware::Stash - The Catalyst stash - in middleware
56
57 =head1 DESCRIPTION
58
59 We've moved the L<Catalyst> stash to middleware.  Please don't use this
60 directly since it is likely to move off the Catalyst namespace into a stand
61 alone distribution
62
63 We store a coderef under the C<PSGI_KEY> which can be dereferenced with
64 key values or nothing to access the underly hashref.
65
66 =head1 SUBROUTINES
67
68 This class defines the following subroutines.
69
70 =head2 PSGI_KEY
71
72 Returns the hash key where we store the stash.  You should not assume
73 the string value here will never change!  Also, its better to use
74 L</get_stash> or L</stash>.
75
76 =head2 get_stash
77
78 Expect: $psgi_env.
79
80 Exportable subroutine.
81
82 Get the stash out of the C<$env>.
83
84 =head2 stash
85
86 Expects: An object that does C<env> and arguments
87
88 Exportable subroutine.
89
90 Given an object with a method C<env> get or set stash values, either
91 as a method or via hashref modification.  This stash is automatically
92 reset for each request (it is not persistent or shared across connected
93 clients.  Stash key / value are stored in memory.
94
95     use Plack::Request;
96     use Catalyst::Middleware::Stash 'stash';
97
98     my $app = sub {
99       my $env = shift;
100       my $req = Plack::Request->new($env);
101       my $stashed = $req->stash->{in_the_stash};  # Assume the stash was previously populated.
102
103       return [200, ['Content-Type' => 'text/plain'],
104         ["I found $stashed in the stash!"]];
105     };
106
107 If the stash does not yet exist, we initialize one and return that.
108
109 =head1 METHODS
110
111 This class defines the following methods.
112
113 =head2 call
114
115 Used by plack to call the middleware
116
117 =cut
118
119 1;