I'm implementing a REST service in php.
q1. Can I split the controller and resource?
http://myserver/myCtrl.php?res=/items/1
q2. if not, is the standard specs (if any exists) for rewrites on iis, apache, nginx etc to survive the http-verb over the rewrite?
If not, how to solve?
For APIs (I have a framework for such) I tend to have a URL structure that looks as follows:
http://domain.com/api/[resource]/[id]/[subresource]
I pass all requests to a front controller with a .htaccess file that parses incoming requests and passes the request off to the relavant controller. So my index.php looks similar to the following at the very simplest:
<?php
$request = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$resource_name = ucfirst($request[0]).'Controller';
$http_verb = strtolower($_SERVER['REQUEST_METHOD']);
$controller = new $resource_name;
$response = call_user_func_array(array($controller, $http_verb), array($request));
header('Content-Type: application/json');
echo json_encode($response);
So if you call http://domain.com/api/news, then it will attempt to instantiate a class called NewsController
, and if it's a GET request then the get()
method of that class, or post()
for a POST request, and so on. The response of that call is then returned to the client as JSON.
Hopefully that should be enough to get you started.
I had some of the same questions and found this video pretty helpful (not standards, but good practices):
http://blog.apigee.com/detail/slides_for_restful_api_design_second_edition_webinar/
I implemented my rest service by rewriting the urls through .htaccess files (mod_rewrite) and a central dispatcher so it looks like this:
http://myserver/myctrl/resource/1
My .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]
</IfModule>
Read more about rewrite: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
I have an index file that does pretty much what Martin outlined. I explode on "/" and assume first is controller, second is action, and the rest are parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With