route.php
Route Handlers facilitate custom request handling for specified routes through Web Request and Response APIs.
Supported HTTP Methods
Route Handlers support various HTTP methods, allowing for flexible request processing. Supported methods include: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.
Example: Basic Usage
To create a publicly accessible route handler, add a route.php file within the app/users/route.php directory and include the following sample code:
<?php
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
// Fetch and encode user data as JSON
$users = $prisma->user->findMany();
echo json_encode($users);
Use any AJAX-capable tool to request data from http://localhost:3000/users and receive a JSON response of user data.
If you want to pass a custom AJAX request Request::$requestedWith = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? ''; you can get the value of the header using the variable Request::$requestedWith witch will return the value of the header, if the header is not set it will return an empty string.
To differentiate request methods, use the following variables within your route handler:
Request::$isGetfor GET requestsRequest::$isPostfor POST requestsRequest::$isPutfor PUT requestsRequest::$isDeletefor DELETE requestsRequest::$isPatchfor PATCH requestsRequest::$isHeadfor HEAD requestsRequest::$isOptionsfor OPTIONS requestsRequest::$contentTypeto determine the content type,Request::$paramsfor accessing request parameters in JSON format.
Example: Handling Specific Methods
Below is an example of configuring route.php to exclusively handle GET requests:
<?php
use Lib\Request;
use Lib\Header\Boom;
use Lib\Prisma\Classes\Prisma;
// Restrict to GET requests, respond with 405 otherwise
if (!Request::$isGet) {
Boom::methodNotAllowed()->toResponse();
}
$prisma = Prisma::getInstance();
// Retrieve users based on query parameters
$users = $prisma->user->findMany([
'where' => [
'id' => Request::$params['id'] ?? '' // Alternative: $_GET['id'] ?? ''
]
]);
echo json_encode($users);
Tip: The Request::$params variable is versatile, allowing access to request parameters across GET, POST, PUT, PATCH, and DELETE methods, either as an alternative or in addition to the traditional $_POST superglobal.