expect people to know what they are doing
[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 Scalar::Util 'blessed';
9 use Carp 'croak';
10
11 our @EXPORT_OK = qw(stash get_stash);
12
13 sub PSGI_KEY { 'Catalyst.Stash.v1' };
14
15 sub get_stash { return shift->{PSGI_KEY} }
16
17 sub generate_stash_closure {
18   my $stash = shift || +{};
19   return sub {
20     if(@_) {
21       my $new_stash = @_ > 1 ? {@_} : $_[0];
22       croak('stash takes a hash or hashref')
23         unless ref $new_stash;
24       foreach my $key ( keys %$new_stash ) {
25         $stash->{$key} = $new_stash->{$key};
26       }
27     }
28     $stash;
29   };
30 }
31
32 sub _init_stash {
33   my ($self, $env) = @_;
34   return $env->{PSGI_KEY} ||=
35     generate_stash_closure;
36 }
37
38 sub stash {
39   my ($host, @args) = @_;
40   return get_stash($host->env)->(@args);
41 }
42
43 sub call {
44   my ($self, $env) = @_;
45   $self->_init_stash($env);
46   return $self->app->($env);
47 }
48
49 =head1 TITLE
50
51 Catalyst::Middleware::Stash - The Catalyst stash - in middleware
52
53 =head1 DESCRIPTION
54
55 We've moved the L<Catalyst> stash to middleware.  Please don't use this
56 directly since it is likely to move off the Catalyst namespace into a stand
57 alone distribution
58
59 We store a coderef under the C<PSGI_KEY> which can be dereferenced with
60 key values or nothing to access the underly hashref.
61
62 =head1 SUBROUTINES
63
64 This class defines the following subroutines.
65
66 =head2 PSGI_KEY
67
68 Returns the hash key where we store the stash
69
70 =head2 get_stash
71
72 Get the stash out of the C<$env>
73
74 =head2 stash
75
76 Exportable subroutine.
77
78 Given an object with a method C<env> get or set stash values, either
79 as a method or via hashref modification.  This stash is automatically
80 reset for each request (it is not persistent or shared across connected
81 clients.  Stash key / value are stored in memory.
82
83     Catalyst::Middleware::Stash 'stash';
84
85     $c->stash->{foo} = $bar;
86     $c->stash( { moose => 'majestic', qux => 0 } );
87     $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
88
89 =head2 generate_stash_closure
90
91 Creates the closure which is stored in the L<PSGI> environment.
92
93 =head1 METHODS
94
95 This class defines the following methods.
96
97 =head2 call
98
99 Used by plack to call the middleware
100
101 =cut
102
103 1;