REST API with Simple-MVC Routing (Example) PHP1 2 3 4 5 6 7// config/route.php return [ [ 'GET', '/api/user[/{id}]', Controller\User::class ], [ 'POST', '/api/user', Controller\User::class ], [ 'PATCH', '/api/user/{id}', Controller\User::class ], [ 'DELETE', '/api/user/{id}', Controller\User::class ] ]; Controller (Example) PHP 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79public class UserController implements ControllerInterface { public function __construct(UserModel $user) { $this->userModel = $user; // Set the Content-type for all the HTTP methods header('Content-type: application/json'); } // method dispatcher public function execute(ServerRequestInterface $request) { $method = strtolower($request->getMethod()); if (!method_exists($this, $method)) { http_response_code(405); // method not exists return; } $this->$method($request); } public function get(ServerRequestInterface $request) { $id = $request->getAttribute('id'); try { $result = empty($id) ? $this->userModel->getAllUsers() : $this->userModel->getUser($id); } catch (UserNotFoundException $e) { http_response_code(404); // user not found $result = ['error' => $e->getMessage()]; } echo json_encode($result); } public function post(ServerRequestInterface $request) { $data = json_decode($request->getBody()->getContents(), true); try { $result = $this->userModel->addUser($data); } catch (InvalidAttributeException $e) { http_response_code(400); // bad request $result = ['error' => $e->getMessage()]; } catch (UserAlreadyExistsException $e) { http_response_code(409); // conflict, the user is not present $result = ['error' => $e->getMessage()]; } echo json_encode($result); } public function patch(ServerRequestInterface $request) { $id = $request->getAttribute('id'); $data = json_decode($request->getBody()->getContents(), true); try { $result = $this->userModel->updateUser($data, $id); } catch (InvalidAttributeException $e) { http_response_code(400); // bad request $result = ['error' => $e->getMessage()]; } catch (UserNotFoundException $e) { http_response_code(404); // user not found $result = ['error' => $e->getMessage()]; } echo json_encode($result); } public function delete(ServerRequestInterface $request) { $id = $request->getAttribute('id'); try { $this->userModel->deleteUser($id); $result = ['result' => 'success']; } catch (UserNotFoundException $e) { http_response_code(404); // user not found $result = ['error' => $e->getMessage()]; } echo json_encode($result); } }