Can I setup routes in Kohana to only match particular HTTP methods (GET/POST/etc)
Asked Answered
L

3

8

I'm exploring a few PHP frameworks and the current front runner is Kohana.

Having a Rails background I've become used to what the rails community calls "RESTful" routes. So a "GET /posts" displays all posts and is handled by the index method of the Posts Controller. A "POST /posts" creates a new post object and is handled by a different method of the Posts Controller.

Since the path in both these 2 requests is identical, the router needs to make decisions based on the HTTP method.

Is the router in Kohana capable of doing this?

Leeanneleeboard answered 15/7, 2009 at 0:25 Comment(0)
B
8

Kohana does not support RESTful routes by default, but there is a RESTful module that adds support for it. See the RESTful wiki for usage.

Kohana v3.x supports RESTful controllers directly. Just extend Controller_REST instead of Controller and all the route action will be the request method. (A POST request would be targeted to action_post, etc.)

Baillieu answered 15/7, 2009 at 3:56 Comment(1)
As of 3.2, the Controller_REST Controller was removed from Kohana core as it was not very RESTful. See: forum.kohanaframework.org/discussion/9004/…Musetta
U
3

You could also add these lines to your controller's before() method:

if ($this->request->method() == "POST")
{
  $this->request->action("post_".$this->request->action());
}

so GET /controller/posts will be handled by the action_posts() method in your controller, while POST /controller/posts will be handled by the action_post_posts() method.

PS: The built-in Controller_REST was removed in Kohana 3.2

Uppity answered 19/8, 2011 at 0:8 Comment(0)
B
0

Checking the HTTP method in the class constructor feels like poor design to me. Like Rails, Kohana 3.3 can create RESTful routes in the router (where they belong).

Check out the documentation for Kohana 3.3 Route Filters.

Here’s an example:

Route::set('Posts', 'posts/<id>', array('id' => '\d+'))
  ->filter(function($route, $params, $request) {
    $params['action'] = strtolower($request->method());
    return $params;
  })
  ->defaults(array(
    'controller' => 'Post',
  ));
Bridgman answered 30/11, 2013 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.