Add docs for ContextClosure.
[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) = @_;
9 my $weak_ctx = $ctx;
10 weaken $ctx;
11 return sub { $closure->($ctx, @_) };
12}
13
141;
c9f762d7 15
16__END__
17
18=head1 NAME
19
20Catalyst::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
42A 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
44closure holds onto a reference to context, and the context holds a reference to
45the closure in its stash. This creates a memory leak, unless you always
46carefully weaken the closures context reference.
47
48This role provides a convenience method to create closures, that closes over
49C<$ctx>.
50
51=head1 METHODS
52
53=head2 make_context_closure ($closure, $ctx)
54
55Returns a code reference, that will invoke C<$closure> with a weakened
56reference to C<$ctx>. All other parameters to the returned code reference will
57be passed along to C<$closure>.
58
59=head1 SEE ALSO
60
61L<Catalyst::Component>
62
63L<Catalyst::Controller>
64
65L<CatalystX::LeakChecker>
66
67=head1 AUTHOR
68
69Florian Ragwitz E<lt>rafl@debian.orgE<gt>
70
71=head1 COPYRIGHT
72
73This library is free software. You can redistribute it and/or modify it under
74the same terms as Perl itself.
75
76=cut