Redirect Methods

A common problem in building web applications is how to best accommodate redirects, while not imposing a lot of repetition in the code. Catalyst provides all the tools using the $c->res->redirect and $c->uri_for methods. That isn't quite enough, though.

Method #1: Redirect Action

I generally enjoy the usage of a "Util" controller class that doesn't have any public facing actions (unless running under debug). In there, a simple private redirect action would look like this:

package MyApp::Controller::Util;
# ... snip ...
sub redirect : Private {
    my ( $self, $c, @uri_args ) = @_;
    # Redirect after a POST should set the status code to 303 instead of 302
    if ( $c->req->method eq 'POST' and $c->res->response == 302 ) {
        $c->res->response(303);
    }
    $c->res->redirect( $c->uri_for( @uri_args ) );
    $c->detach;
}

Then to use this action, anywhere in your app you can write:

$c->forward('/util/redirect', [ $c->controller('PostRedirect')->action_for('controller') ] );

Now, the reason why I use a controller action rather than a plugin or method directly attached to $c like the oft proposed $c->redirect is because sometimes you don't know how your application is going to have to redirect. In certain cases, you are running behind some sort of a proxy or interface that strips away the headers. The most high profile example of this is inside of a Facebook application.

If your application is generating Facebook's markup language (FBML) then you must redirect using that. So, the simple solution is to incrementally modify your /util/redirect method to be more intelligent about the request and redirect accordingly.

-- J. Shirley, 2008-03-20 15:50:31

My tags:
 
Popular tags:
 
Powered by Catalyst
Powered by MojoMojo Hosted by Shadowcat - Managed by Nordaaker