Extending Catalyst::Response

| 1 Comment | No TrackBacks

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

No TrackBacks

TrackBack URL: http://perl.stirbu.name/cgi-bin/mt-tb.cgi/7

1 Comment

Note that this sort of technique is used on the request class by Catalyst::Action::REST and Catalyst::Plugin::Server.

Several people have popped up on irc at various points to point out how they don't play nicely together - fail!

The only solution is to make MyApp::Request, which inherits from the other two - horrible..

The correct solution to this is to make it a role rather than a subclass, and use CatalystX::RoleApplicator.

Leave a comment

About this Entry

This page contains a single entry by Viorel published on April 30, 2009 10:04 PM.

Perl iron-man initiative and taking the first step was the previous entry in this blog.

Kill Perl is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

OpenID accepted here Learn more about OpenID
Powered by Movable Type 4.25