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::$isGet for GET requests
  • Request::$isPost for POST requests
  • Request::$isPut for PUT requests
  • Request::$isDelete for DELETE requests
  • Request::$isPatch for PATCH requests
  • Request::$isHead for HEAD requests
  • Request::$isOptions for OPTIONS requests
  • Request::$contentType to determine the content type,
  • Request::$params for 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);