cleaned up stash interface
[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) if
41     $host->can('env');
42 }
43
44 sub call {
45   my ($self, $env) = @_;
46   $self->_init_stash($env);
47   return $self->app->($env);
48 }
49
50 =head1 TITLE
51
52 Catalyst::Middleware::Stash - The Catalyst stash - in middleware
53
54 =head1 DESCRIPTION
55
56 We've moved the L<Catalyst> stash to middleware.  Please don't use this
57 directly since it is likely to move off the Catalyst namespace into a stand
58 alone distribution
59
60 We store a coderef under the C<PSGI_KEY> which can be dereferenced with
61 key values or nothing to access the underly hashref.
62
63 =head1 SUBROUTINES
64
65 This class defines the following subroutines.
66
67 =head2 PSGI_KEY
68
69 Returns the hash key where we store the stash
70
71 =head2 get_stash
72
73 Get the stash out of the C<$env>
74
75 =head2 stash
76
77 Exportable subroutine.
78
79 Given an object with a method C<env> get or set stash values, either
80 as a method or via hashref modification.  This stash is automatically
81 reset for each request (it is not persistent or shared across connected
82 clients.  Stash key / value are stored in memory.
83
84     Catalyst::Middleware::Stash 'stash';
85
86     $c->stash->{foo} = $bar;
87     $c->stash( { moose => 'majestic', qux => 0 } );
88     $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
89
90 =head2 generate_stash_closure
91
92 Creates the closure which is stored in the L<PSGI> environment.
93
94 =head1 METHODS
95
96 This class defines the following methods.
97
98 =head2 call
99
100 Used by plack to call the middleware
101
102 =cut
103
104 1;