Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 471
Ha Sh Avatar asked Nov 08 '12 16:11

Ha Sh


1 Answers

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.

like image 59
memowe Avatar answered Nov 18 '22 07:11

memowe