Merge branch 'abort-chain-doc-and-test' of https://github.com/melmothx/catalyst-runti...
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Component / ContextClosure.pm
CommitLineData
5ad8be8c 1package Catalyst::Component::ContextClosure;
2
3use Moose::Role;
4use Scalar::Util 'weaken';
5use namespace::autoclean;
6
7sub make_context_closure {
8 my ($self, $closure, $ctx) = @_;
5ad8be8c 9 weaken $ctx;
10 return sub { $closure->($ctx, @_) };
11}
12
131;
c9f762d7 14
15__END__
16
17=head1 NAME
18
19Catalyst::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
41A 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
43closure holds onto a reference to context, and the context holds a reference to
44the closure in its stash. This creates a memory leak, unless you always
45carefully weaken the closures context reference.
46
47This role provides a convenience method to create closures, that closes over
48C<$ctx>.
49
50=head1 METHODS
51
52=head2 make_context_closure ($closure, $ctx)
53
54Returns a code reference, that will invoke C<$closure> with a weakened
55reference to C<$ctx>. All other parameters to the returned code reference will
56be passed along to C<$closure>.
57
58=head1 SEE ALSO
59
60L<Catalyst::Component>
61
62L<Catalyst::Controller>
63
64L<CatalystX::LeakChecker>
65
8ad6fd58 66=begin stopwords
67
c9f762d7 68=head1 AUTHOR
69
eb67e0f6 70Florian Ragwitz <rafl@debian.org>
c9f762d7 71
8ad6fd58 72=end stopwords
73
c9f762d7 74=head1 COPYRIGHT
75
76This library is free software. You can redistribute it and/or modify it under
77the same terms as Perl itself.
78
79=cut