3 # Created by: Adam Jacob, Marchex, <adam@marchex.com>
4 # Created on: 10/12/2006 03:00:32 PM PDT
8 package Catalyst::Action::REST;
13 use base 'Catalyst::Action';
22 Catalyst::Action::REST - Automated REST Method Dispatching
26 sub foo :Local :ActionClass('REST') {}
29 ... do something for GET requests ...
33 ... do somethign for PUT requests ...
38 This Action handles doing automatic method dispatching for REST requests. It
39 takes a normal Catalyst action, and changes the dispatch to append an
40 underscore and method name.
42 For example, in the synopsis above, calling GET on "/foo" would result in
43 the foo_GET method being dispatched.
45 If a method is requested that is not implemented, this action will
46 return a status 405 (Method Not Found). It will populate the "Allow" header
47 with the list of implemented request methods.
49 It is likely that you really want to look at L<Catalyst::Controller::REST>.
57 This method overrides the default dispatch mechanism to the re-dispatching
58 mechanism described above.
66 my $controller = $self->class;
67 my $method = $self->name . "_" . uc( $c->request->method );
68 if ( $controller->can($method) ) {
69 $c->execute( $self->class, $self, @{ $c->req->args } );
70 return $controller->$method( $c, @{ $c->req->args } );
72 if ( $c->request->method eq "OPTIONS" ) {
73 return $self->_return_options($c);
75 my $handle_ni = $self->name . "_not_implemented";
76 if ( $controller->can($handle_ni) ) {
77 return $controller->$handle_ni( $c, @{ $c->req->args } );
79 return $self->_return_not_implemented($c);
86 my ( $self, $c ) = @_;
88 my @allowed = $self->_get_allowed_methods($c);
89 $c->response->content_type('text/plain');
90 $c->response->status(200);
91 $c->response->header( 'Allow' => \@allowed );
94 sub _get_allowed_methods {
95 my ( $self, $c ) = @_;
97 my $controller = $self->class;
98 my $methods = Class::Inspector->methods($controller);
100 foreach my $method ( @{$methods} ) {
101 my $name = $self->name;
102 if ( $method =~ /^$name\_(.+)$/ ) {
103 push( @allowed, $1 );
109 sub _return_not_implemented {
110 my ( $self, $c ) = @_;
112 my @allowed = $self->_get_allowed_methods($c);
113 $c->response->content_type('text/plain');
114 $c->response->status(405);
115 $c->response->header( 'Allow' => \@allowed );
116 $c->response->body( "Method "
117 . $c->request->method
118 . " not implemented for "
119 . $c->uri_for( $self->reverse ) );
128 You likely want to look at L<Catalyst::Controller::REST>, which implements
129 a sensible set of defaults for a controller doing REST.
131 L<Catalyst::Action::Serialize>, L<Catalyst::Action::Deserialize>
135 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
137 Marchex, Inc. paid me while I developed this module. (http://www.marchex.com)
141 Daisuke Maki <daisuke@endeworks.jp>
145 You may distribute this code under the same terms as Perl itself.