PHP code example of yohan / rest-flex-php

1. Go to this page and download the library: Download yohan/rest-flex-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yohan / rest-flex-php example snippets



use RestFlexPHP\RestFlexController;
use RestFlexPHP\RestFlexRequest;

// Retrieving a controller instance
$controller = RestFlexController::getController();

// Define a route for GET requests
$controller->get('/users/{id}', function (RestFlexRequest $request) {
    // Handle the GET request for the "/users/{id}" path
    $userId = $request->pathVariables['id'];
    
    // Your custom logic here...
    
    // Finally send the response to the client
    $request->sendResponse($data, HttpStatus::OK);
});

// Other route definitions...

// Handle unmatched routes
$controller->noMapping(function (RestFlexRequest $request) {
    // Handle unmatched routes or provide a default 404 response
    $request->sendResponse('Route not found', HttpStatus::NOT_FOUND);
});


use RestFlexPHP\RestFlexController as RFC;
use RestFlexPHP\RestFlexRequest as RFR;

class UserController
{
    public function __construct(RFC $controller)
    {
        $controller->get('users/getAllUsers', [$this, 'getAllUsers']);
        $controller->get('users/getUser/{id}', [$this, 'getUser']);
    }

    public function getAllUsers(RFR $req)
    {
        $req->sendResponse(/* all your users */);
    }

    public function getUser(RFR $req)
    {
        $userId = $req->pathVariables['id'];
        // $user = your logic to find user by user id from the database.
        $req->sendResponse($user);
    }
}


use RestFlexPHP\RestFlexController;

$controller = RestFlexController::getController();

// Instantiate UserController, which will define routes
new UserController($controller);

// Handle unmatched routes
$controller->noMapping();

$controller->put('/users/{id}', function (RestFlexRequest $request) {
    // Access path variables using pathVariables array
    $userId = $request->pathVariables['id'];
    
    // Access request body using body property
    $data = $request->body;
    
    // Access URL query parameters using params property
    $params = $request->params;
    
    // Finally send the response back to the client
    $request->sendResponse($data, HttpStatus::OK);
});