Extending Catalyst::Response

This is how to extend the functionality of Catalyst::Response (and other components in a similar way). For example I would like better default response codes for redirect so I will extend Catalyst::Response into MyApp::Response and override ("around" to be more precise) the redirect method. In order to tell Catalyst to use this response class I will write this in MyApp :

# Override Catalyst::Response class
use MyApp::Response;
__PACKAGE__->response_class('MyApp::Response');

Here is the content of MyApp::Response file :

 package MyApp::Response;
 use Moose;
 extends 'Catalyst::Response';

 around 'redirect' => sub {
     my $orig = shift;
     my $self = shift;
     my ($location, $status) = @_;

     # Behave as an accessor
     return $self->$orig() unless @_;  

     my $method = $self->_context->request->method;

     # Set better defaults for response codes
     # http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307
     unless ($status) {
         if ($method eq 'GET' or $method eq 'HEAD') {
             $status = 301; # Moved Permanently
         }
         elsif ($method eq 'POST') {
             $status = 303; # See Other (POST-Redirect-GET pattern)
         }
     }

     return $self->$orig($location, $status);
 };

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