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