Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basics of REST with php

Tags:

rest

php

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

Anyway, in this code snippet the author is showing the basics of how a website may use something like www.example.com/restaurant/42 instead of /?restaurant_ID=42.

Can anyone explain why this is used

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

For this example they would generate the same array, but what if it's a longer path such as Restaurant/item/3 ? Wouldn't you want to separate everything? As you can see, further down in this block they do use explode without defining a limit. Is the first one simply for the resource? (I guess the controller if it were an 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");
}
like image 962
user1104854 Avatar asked Aug 27 '12 12:08

user1104854


1 Answers

It's first splitting the entire path into a resource and a params variable. $resource will contain the first element, $params the rest. For instance:

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

Then, the $params string is further broken down into individual items:

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

Essentially it's treating the first part special.

You could get the same effect with this:

$params   = explode('/', $path);
$resource = array_shift($params);
like image 180
deceze Avatar answered Sep 23 '22 08:09

deceze