Kohana Route for API - Subdirectories, ids, formats
-
14-06-2021 - |
Question
I'm trying to create a route in Kohana 3.2 that would match URIs like
api/article/get.json
api/article/get/123.xml
api/blogpost/post.json
api/user/get/username.json
So the idea is that I have a sub directory called API where I have all my api controllers, the route matches the controller, the method, a format, and alternatively and id.
I have set the following rout in my application/bootstrap.php
Route::set('api', 'api/<controller>(/<action>(/<id>).<format>)',
array(
'format' => '(xhtml|xml|json|rss|html|php|serialize)',
))
->defaults(array(
'directory' => 'api',
'controller' => 'blogposts',
'action' => 'get',
'format' => 'json',
));
I have played with multiple combinations of this route, but every time I get the following error message for a url like: localhost/api/blogposts/post.json
HTTP_Exception_404 [ 404 ]: The requested URL api/blogposts/post.php was not found on this server.
It seems to me that this should be fine, but I must be doing something wrong.
Help is appreciated.
Onema
EDIT
My default controller is set to be last, just thought I would mention it as I found this post in SO Kohana 3 route not matching
Solution
This is probably a newb mistake but the problem was not the route, rather the class name here is why:
I placed my controller in
application/classes/controller/api/bloposts.php
And the name of the class was
class Controller_Blogposts extends Controller {
...
}
After spending some time debugging the application I found that the issue was not the route so much as the name of the class which should have been
class Controller_Api_Blogposts extends Controller {
...
}
As the autoloader will map the route api/blogposts.json
to the class "Controller_Api_Blogposts".
In the Kohana 3.2 Conventions and Coding Style, they have a nice table that shows what the class name is and what the file path should be:
I'm not sure 100% the technicalities behind route mapping with directories, but If the route maps to a <directory>
(in this case is api) it is safe to assume that api is with in the "application/classes/controller" directory.