· 4 years ago · Mar 24, 2021, 09:06 PM
1<?php
2
3 /*
4 Step 1:
5 A simple function to respond with the correct headers
6 and status code. Will convert the response into JSON.
7 */
8 function response ($code, $message) {
9 http_response_code($code);
10 header("Content-Type: application/json");
11 echo json_encode($message);
12 }
13
14 /*
15 The connect function will be availabe to any of our
16 subsequent included files. This means that to interact
17 with our connection, we simply call "dbo()" anywhere.
18 */
19 require_once("connect.php");
20
21 /*
22 Step 2: A ReSTful API requires us to be able to understand the
23 request path provided, as it will determine the key parts
24 needed to build the proper response.
25 */
26 $resolved_path = str_replace(dirname($_SERVER['PHP_SELF']), '', $_SERVER['REQUEST_URI']);
27
28 /*
29 Step 3: The "parts" are the various pieces of our requested path,
30 sorted by concern.
31 */
32 $parts = explode("/", $resolved_path);
33 $root = $parts[0];
34 $resource = $parts[1];
35 $action = empty($parts[2]) ? "index" : $parts[2];
36 $params = isset($parts[3]) ? array_slice($parts, 3, count($parts)) : [];
37
38 /*
39 Step 4: This is the HTTP method used to make the request
40 */
41 $request_method = $_SERVER['REQUEST_METHOD'];
42
43 /*
44 Step 5: The logic below first attempts to see if a resource
45 has been defined (ie: "contacts").
46 */
47 if ($resource) {
48 require_once("{$resource}/controller.php");
49
50 switch ($action) {
51 case "show":
52 case "search":
53 case "index":
54 if ($request_method !== "GET") {
55 response(404, ["status" => "Not Found"]);
56 }
57 break;
58 case "create":
59 case "update":
60 case "delete":
61 if ($request_method !== "POST") {
62 response(404, ["status" => "Not Found"]);
63 }
64 break;
65 }
66
67 return call_user_func_array($action, $params);
68 }