Commit | Line | Data |
5ad8be8c |
1 | package Catalyst::Component::ContextClosure; |
2 | |
3 | use Moose::Role; |
4 | use Scalar::Util 'weaken'; |
5 | use namespace::autoclean; |
6 | |
7 | sub make_context_closure { |
8 | my ($self, $closure, $ctx) = @_; |
5ad8be8c |
9 | weaken $ctx; |
10 | return sub { $closure->($ctx, @_) }; |
11 | } |
12 | |
13 | 1; |
c9f762d7 |
14 | |
15 | __END__ |
16 | |
17 | =head1 NAME |
18 | |
19 | Catalyst::Component::ContextClosure - Moose Role for components which need to close over the $ctx, without leaking |
20 | |
21 | =head1 SYNOPSIS |
22 | |
23 | package MyApp::Controller::Foo; |
24 | use Moose; |
9a991f0e |
25 | use namespace::clean -except => 'meta'; |
c9f762d7 |
26 | BEGIN { |
27 | extends 'Catalyst::Controller'; |
28 | with 'Catalyst::Component::ContextClosure'; |
29 | } |
30 | |
31 | sub some_action : Local { |
32 | my ($self, $ctx) = @_; |
33 | $ctx->stash(a_closure => $self->make_context_closure(sub { |
34 | my ($ctx) = @_; |
35 | $ctx->response->body('body set from closure'); |
432c4971 |
36 | }, $ctx)); |
c9f762d7 |
37 | } |
38 | |
39 | =head1 DESCRIPTION |
40 | |
41 | A common problem with stashing a closure, that closes over the Catalyst context |
42 | (often called C<$ctx> or C<$c>), is the circular reference it creates, as the |
43 | closure holds onto a reference to context, and the context holds a reference to |
44 | the closure in its stash. This creates a memory leak, unless you always |
45 | carefully weaken the closures context reference. |
46 | |
47 | This role provides a convenience method to create closures, that closes over |
48 | C<$ctx>. |
49 | |
50 | =head1 METHODS |
51 | |
52 | =head2 make_context_closure ($closure, $ctx) |
53 | |
54 | Returns a code reference, that will invoke C<$closure> with a weakened |
55 | reference to C<$ctx>. All other parameters to the returned code reference will |
56 | be passed along to C<$closure>. |
57 | |
58 | =head1 SEE ALSO |
59 | |
60 | L<Catalyst::Component> |
61 | |
62 | L<Catalyst::Controller> |
63 | |
64 | L<CatalystX::LeakChecker> |
65 | |
8ad6fd58 |
66 | =begin stopwords |
67 | |
c9f762d7 |
68 | =head1 AUTHOR |
69 | |
70 | Florian Ragwitz E<lt>rafl@debian.orgE<gt> |
71 | |
8ad6fd58 |
72 | =end stopwords |
73 | |
c9f762d7 |
74 | =head1 COPYRIGHT |
75 | |
76 | This library is free software. You can redistribute it and/or modify it under |
77 | the same terms as Perl itself. |
78 | |
79 | =cut |