How to call action in some other controller in Mojolicious?
Asked Answered
S

1

13

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 ($self) 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?

Spread answered 8/11, 2012 at 16:52 Comment(0)
F
10

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 something (e.g. databases) for some actions, maybe under is helpful for you:

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

PS: This feature of Mojolicious was previously named Bridges. Answer updated accordingly.

Famagusta answered 8/11, 2012 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.