REST basics with php

I'm trying to learn the basics of REST and I found a pretty good tutorial (at least it helped me understand the basics). This is the tutorial that I used .

In any case, in this code fragment, the author shows the basics of how a website can use something like www.example.com/restaurant/42 instead of /?restaurant_ID=42 .

Can someone explain why this is used

 explode("/", $path, 2); instead of explode("/", $path); 

In this example, they will generate the same array, but what if it has a longer path, such as Restaurant/item/3 ? Wouldn't you like to separate everything? As you can see, later in this block they use an explosion without defining a limit. Is the first for a resource? (I think the controller if it is MVC)

 <?php // assume autoloader available and configured $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); $path = trim($path, "/"); @list($resource, $params) = explode("/", $path, 2); //why is limit used here? $resource = ucfirst(strtolower($resource)); $method = strtolower($_SERVER["REQUEST_METHOD"]); $params = !empty($params) ? explode("/", $params) : array(); //no limit here? if (class_exists($resource)) { try { $resource = new $resource($params); $resource->{$method}(); } catch (Exception $e) { header("HTTP/1.1 500 Internal Server Error"); } } else { header("HTTP/1.1 404 File Not Found"); } 
+6
source share
1 answer

First, it splits the entire path into a resource and params variable. $resource will contain the first element, $params rest. For instance:

 restaurant/42 -> restaurant, 42 restaurant/item/3 -> restaurant, item/3 foo/bar/baz/boom -> foo, bar/baz/boom 

Then the line $params further broken down into separate elements:

 restaurant/42 -> restaurant, (42) restaurant/item/3 -> restaurant, (item, 3) foo/bar/baz/boom -> foo, (bar, baz, boom) 

Essentially, it handles the first part of a special one.

You can get the same effect:

 $params = explode('/', $path); $resource = array_shift($params); 
+6
source

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


All Articles