Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST practicices on PHP, rewrite and http-verbs

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?

like image 944
Teson Avatar asked Jan 12 '12 12:01

Teson


2 Answers

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.

like image 122
Martin Bean Avatar answered Nov 07 '22 03:11

Martin Bean


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.

like image 26
James Cowhen Avatar answered Nov 07 '22 01:11

James Cowhen