PHP code example of hnqca / router-php

1. Go to this page and download the library: Download hnqca/router-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/ */

    

hnqca / router-php example snippets




nqca\Router\Router;
use Hnqca\Router\Request;
use Hnqca\Router\Response;

/**
 * Examples of Middleware classes
 */
oller.php';
R__ . '/Controllers/ErrorController.php';

use Controllers\HomeController;
use Controllers\ProductController;
use Controllers\UserController;
use Controllers\AdminController;
use Controllers\ErrorController;

/**
 * Routes
 */
$route = new Router();

$route->get('/',         [HomeController::class,     'index']);
$route->get("/products", [ProductController::class,  'index']);


/**
 * Route without a controller class
 */
$route->get('/hello/{name}', [], function(Request $req, Response $res){

    $name = $req->getParams()->name;
    
    return $res->send(200, "Hello, {$name}!");
});

/**
 * Route with middleware
 */
$route->get('/admin', [AdminController::class, 'index'], function () {
    return (new AuthMiddleware)->onlyAdmin();
});


/**
 * Example of routes for CRUD operations
 */
$route->post("/users",        [UserController::class,  'create']);
$route->get("/users",         [UserController::class,  'index']);
$route->get("/users/{id}",    [UserController::class,  'show']);
$route->put("/users/{id}",    [UserController::class,  'update']);
$route->patch("/users/{id}",  [UserController::class,  'update']);
$route->delete("/users/{id}", [UserController::class,  'delete']);


/**
 * Execute
 */
$route->dispatch();


/**
 * Example for error handling in the route
 * 404 Not Found, 405 Method Not Allowed and 501 Not Implemented
 */
if ($route->error()) {
    return (new ErrorController)->show($route->error());
}

$route->get("/users/{id}", [UserController::class, 'show']);

class UserController
{
    public function show(Request $req, Response $res)
    {
        // var_dump($req->getParams());

        $userId = $req->getParams()->id;

        if (!filter_var($userId, FILTER_VALIDATE_INT)) {
            return $res->send(400, "It is expected to receive a value of integer type.");
        }
        
        return $res->send(200, "Viewing user data with ID: {$userId}");
    }
}

$route->get("/products", [ProductControllers::class, 'index']);

class ProductController
{
    public function index(Request $req, Response $res)
    {
        $filter = $req->getQuery()->filter ?? null;

        if ($filter) {
            return $res->send(200, "Filtering products by {$filter}"); 
        }

        return $res->send(200, "Listing all products..."); 
    }
}
bash
composer 
bash
location / {
  if ($script_filename !~ "-f"){
    rewrite ^(.*)$ /index.php?uri=/$1 break;
  }
}