Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

How to get the Catalyst Context object

by Sewi (Friar)
on Nov 07, 2015 at 06:59 UTC ( [id://1147171]=perlquestion: print w/replies, xml ) Need Help??

Sewi has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

I need to access the current context object for a catalyst request outside of the controller and without passing it from the controller.

A typical catalyst controller:

sub index :Path :Args(0) { my ( $self, $c ) = @_; # Hello World $c->response->body( $c->welcome_message ); }

How to get $c in other modules without explicit passing it?

My current solution is setting a global variable in my root controller...

package MyApp::Controller::Root; our $C; sub auto :Private { my ($self, $c) = @_; $C = $c; }
...and accessing it as $MyApp::Controller::Root::C, but I'd prefer to use the "official" way and to be compatible with any Catalyst App without changing it.

Thank you.

Replies are listed 'Best First'.
Re: How to get the Catalyst Context object
by Your Mother (Archbishop) on Nov 08, 2015 at 02:04 UTC

    I agree that it tends to be design smell to need it but sometimes it's just the most natural way to solve a problem. I've done it three times, I think, and ended up taking one back when I realized my design error. This is the current best way to do it: Catalyst::Component::ApplicationAttribute.

    # Moose extends etc with "Catalyst::Component::ApplicationAttribute"; sub somesub { my $self = shift; my $ctx = $self->_application; }

    It handled handles the weakening properly and with the leading underscore emphasizes the private/dangerous nature of its usage.

Re: How to get the Catalyst Context object
by Anonymous Monk on Nov 07, 2015 at 07:54 UTC

    How to get $c in other modules without explicit passing it?

    Pass it

    only controller should have access to the context, that is a design goal

    if something other than controller depends context, its a design mistake (tight coupling)

Re: How to get the Catalyst Context object
by Anonymous Monk on Nov 07, 2015 at 07:58 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1147171]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (7)
As of 2024-04-18 17:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found