1 package Catalyst::Component::ContextClosure;
4 use Scalar::Util 'weaken';
5 use namespace::autoclean;
7 sub make_context_closure {
8 my ($self, $closure, $ctx) = @_;
10 return sub { $closure->($ctx, @_) };
19 Catalyst::Component::ContextClosure - Moose Role for components which need to close over the $ctx, without leaking
23 package MyApp::Controller::Foo;
25 use namespace::clean -except => 'meta';
27 extends 'Catalyst::Controller';
28 with 'Catalyst::Component::ContextClosure';
31 sub some_action : Local {
32 my ($self, $ctx) = @_;
33 $ctx->stash(a_closure => $self->make_context_closure(sub {
35 $ctx->response->body('body set from closure');
41 A 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
43 closure holds onto a reference to context, and the context holds a reference to
44 the closure in its stash. This creates a memory leak, unless you always
45 carefully weaken the closures context reference.
47 This role provides a convenience method to create closures, that closes over
52 =head2 make_context_closure ($closure, $ctx)
54 Returns a code reference, that will invoke C<$closure> with a weakened
55 reference to C<$ctx>. All other parameters to the returned code reference will
56 be passed along to C<$closure>.
60 L<Catalyst::Component>
62 L<Catalyst::Controller>
64 L<CatalystX::LeakChecker>
68 Florian Ragwitz E<lt>rafl@debian.orgE<gt>
72 This library is free software. You can redistribute it and/or modify it under
73 the same terms as Perl itself.