1 package Catalyst::Component::ContextClosure;
4 use Scalar::Util 'weaken';
5 use namespace::autoclean;
7 sub make_context_closure {
8 my ($self, $closure, $ctx) = @_;
11 return sub { $closure->($ctx, @_) };
20 Catalyst::Component::ContextClosure - Moose Role for components which need to close over the $ctx, without leaking
24 package MyApp::Controller::Foo;
26 use namespace::autoclean;
28 extends 'Catalyst::Controller';
29 with 'Catalyst::Component::ContextClosure';
32 sub some_action : Local {
33 my ($self, $ctx) = @_;
34 $ctx->stash(a_closure => $self->make_context_closure(sub {
36 $ctx->response->body('body set from closure');
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.
48 This role provides a convenience method to create closures, that closes over
53 =head2 make_context_closure ($closure, $ctx)
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>.
61 L<Catalyst::Component>
63 L<Catalyst::Controller>
65 L<CatalystX::LeakChecker>
69 Florian Ragwitz E<lt>rafl@debian.orgE<gt>
73 This library is free software. You can redistribute it and/or modify it under
74 the same terms as Perl itself.