expect people to know what they are doing
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Middleware / Stash.pm
CommitLineData
6561feae 1use strict;
2use warnings;
561098d1 3
4package Catalyst::Middleware::Stash;
5
6561feae 6use base 'Plack::Middleware';
561098d1 7use Exporter 'import';
8use Scalar::Util 'blessed';
9use Carp 'croak';
10
11our @EXPORT_OK = qw(stash get_stash);
6561feae 12
13sub PSGI_KEY { 'Catalyst.Stash.v1' };
14
561098d1 15sub get_stash { return shift->{PSGI_KEY} }
16
17sub 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
6561feae 32sub _init_stash {
33 my ($self, $env) = @_;
561098d1 34 return $env->{PSGI_KEY} ||=
35 generate_stash_closure;
6561feae 36}
37
561098d1 38sub stash {
39 my ($host, @args) = @_;
02c4d598 40 return get_stash($host->env)->(@args);
6561feae 41}
42
43sub call {
44 my ($self, $env) = @_;
45 $self->_init_stash($env);
46 return $self->app->($env);
47}
48
49=head1 TITLE
50
51Catalyst::Middleware::Stash - The Catalyst stash - in middleware
52
53=head1 DESCRIPTION
54
55We've moved the L<Catalyst> stash to middleware. Please don't use this
56directly since it is likely to move off the Catalyst namespace into a stand
57alone distribution
58
561098d1 59We store a coderef under the C<PSGI_KEY> which can be dereferenced with
60key values or nothing to access the underly hashref.
6561feae 61
561098d1 62=head1 SUBROUTINES
63
64This class defines the following subroutines.
6561feae 65
66=head2 PSGI_KEY
67
68Returns the hash key where we store the stash
69
561098d1 70=head2 get_stash
6561feae 71
72Get the stash out of the C<$env>
73
561098d1 74=head2 stash
75
76Exportable subroutine.
77
78Given an object with a method C<env> get or set stash values, either
79as a method or via hashref modification. This stash is automatically
80reset for each request (it is not persistent or shared across connected
81clients. 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
91Creates the closure which is stored in the L<PSGI> environment.
92
93=head1 METHODS
94
95This class defines the following methods.
96
6561feae 97=head2 call
98
99Used by plack to call the middleware
100
101=cut
102
1031;