I'm building an example REST API in PHP in my local environment to learn how they work. The starting point was an online tutorial. The example is working fine; however, I have a hunch that there is room for improvement in the logic that handles the endpoints which is stored in a script called RestController.php
.
Currently, I have the example working both via a UI and, separately, using Postman. The pertinent lines in .htaccess
file are:
RewriteRule ^mobile/?$ controllers/RestController.php [nc,L]
RewriteRule ^mobile/([0-9]+)/?$ controllers/RestController.php?id=$1 [nc,qsa,L]
Here is an example of a Postman test for the GET one mobile API endpoint:
The code that follows is RestController.php. I'm wondering if there is a way to refactor this into a class but still have the ability to use Postman for testing the endpoints. If so, how would one go about doing that?
<?php
require_once("../classes/MobileRestHandler.php");
# read raw data from request body and stuff it into $_POST
$_POST = json_decode(file_get_contents('php://input'), true);
# get parameter values according to the method
$method = $_SERVER['REQUEST_METHOD'];
# initialize and populate $parameters_* variables
if (in_array($method, ['GET', 'PUT', 'DELETE'])) {
$id = isset($_GET["id"]) ? $_GET["id"] : "";
$parameters_id_only = ['id' => $id];
}
if (in_array($method, ['POST', 'PUT'])) {
$name = isset($_POST["name"]) ? $_POST["name"] : "";
$model = isset($_POST["model"]) ? $_POST["model"] : "";
$color = isset($_POST["color"]) ? $_POST["color"] : "";
$parameters_no_id = ['name' => $name, 'model' => $model, 'color' => $color];
}
if ($method == 'PUT') {
$parameters_all = array_merge($parameters_id_only, $parameters_no_id);
}
# this logic controls the RESTful services URL mapping
$mobileRestHandler = new MobileRestHandler();
if (!in_array($method, ['GET', 'POST', 'PUT', 'DELETE'])) {
$statusCode = 404;
$statusMessage = $mobileRestHandler->getHttpStatusMessage($statusCode);
exit($statusCode . ' - ' . $statusMessage);
} else {
if ($method == 'GET' && strlen($id) == 0) {
$result = $mobileRestHandler->getAllMobiles(); // handles method GET + REST URL /mobile/
} else if ($method == 'GET') {
$result = $mobileRestHandler->getMobile($parameters_id_only); // handles method GET + REST URL /mobile/<id>/
} else if ($method == 'POST') {
$result = $mobileRestHandler->addMobile($parameters_no_id); // handles method POST + REST URL /mobile/
} else if ($method == 'PUT') {
$result = $mobileRestHandler->editMobile($parameters_all); // handles method PUT + REST URL /mobile/<id>/
} else if ($method == 'DELETE') {
$result = $mobileRestHandler->deleteMobile($parameters_id_only); // handles method DELETE + REST URL /mobile/<id>/
}
echo $result;
}
?>