Ha Sh Ha Sh - 1 year ago 84
Perl Question

How to call action in some other controller in Mojolicious?

I have an application that uses the Mojolicious framework. I have a table in the database that has a list of error response and additional details associated with it. I have created corresponding Result and Resultset to work with the DB table. There is also a controller to get details about the Error by interacting with the Resultset.

My idea is to Call an action in this controller that would get the details of the error that is passed to it (by another controller) by querying the database, add-in runtime information about the environment that requested for the resource that resulted in the error, create a response and return to the controller that called it.

I am struggling with the call from one controller to another. How do I do it in Mojolicious? I can pass the controller object (

) to accomplish this, but is there a better way to do it, so that I separate entirely my error handling response from the calling controller?

Answer Source

In Mojolicious, you would probably want to pass that object around with a helper without creating a Mojolicious::Controller out of it:

In your main class:

sub startup {
    my $app = shift;

    # ...
    my $thing = Thing->new(foo => 42);
    $app->helper(thing => sub {$thing});

In your controller:

sub cool_action {
    my $c = shift;

    # ...
    my $foo = $c->thing->gimmeh_foo('bar');
    # ...

However, if you would like to prepare some database stuff for some actions, maybe bridges are for you:

To share code with multiple nested routes you can [...]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download