Well, that got forgotten, oops
[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;
25 use namespace::autoclean;
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');
36 }, $ctx);
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
66=head1 AUTHOR
67
68Florian Ragwitz E<lt>rafl@debian.orgE<gt>
69
70=head1 COPYRIGHT
71
72This library is free software. You can redistribute it and/or modify it under
73the same terms as Perl itself.
74
75=cut