PHP REST practices, rewriting, and http verbs

I am implementing a REST service in php.

q1. Is it possible to separate the controller and the resource?

http://myserver/myCtrl.php?res=/items/1 

q2. if not, are the standard specifications (if they exist) for rewriting on iis, apache, nginx, etc. to survive the http verb over rewriting?

If not, how to solve?

+4
source share
2 answers

For APIs (I have a basis for this), I tend to have a URL structure that looks like this:

http://domain.com/api/[resource 022/[ID.BIZ/[subresource]

I pass all requests to the front controller with a .htaccess file that parses incoming requests and passes the request to the relavant controller. So my index.php looks something like this:

 <?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 try to instantiate a class called NewsController , and if it is GET then get() request for a method of this class or post() for a POST request, etc. . The response of this call is then returned to the client as JSON.

Hope this should be enough for you to get started.

+3
source

I had the same questions, and I found this video very useful (not standards, but good practices):

http://blog.apigee.com/detail/slides_for_restful_api_design_second_edition_webinar/

I performed my rest service by rewriting the URLs through the .htaccess files (mod_rewrite) and the central dispatcher so that it looked 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> 

More about rewriting: http://httpd.apache.org/docs/current/mod/mod_rewrite.html

I have an index file that pretty much does what Martin was talking about. I explode on "/" and assume that first it is the controller, the second is the action, and the rest are the parameters.

+2
source

Source: https://habr.com/ru/post/1390630/


All Articles