PHP code example of php-compatible / router

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

    

php-compatible / router example snippets



er(function() {
    route(method(GET), url_path('/'), function() {
        echo 'Welcome!';
    });

    route(method(GET), url_path('/users/:id'), function() {
        $id = $_GET[':id'];
        echo json_response(HTTP_OK, array('id' => $id));
    });

    route(method(POST), url_path('/users'), function() {
        // Create user
        echo json_response(HTTP_CREATED, array('status' => 'created'));
    });
});

// Before: routing logic buried in index.php with dozens of ion() {
    route(method(GET), url_path('/products'), 'show_products');
    route(method(GET), url_path('/products/:id'), 'show_product');
    route(method(POST), url_path('/products'), 'create_product');
});

router(function() {
    routerGroup('/api', function() {
        middleware(function() {
            if (!is_authenticated()) {
                echo json_response(HTTP_UNAUTHORIZED, array('error' => 'Unauthorized'));
                return false;
            }
            return true;
        });

        route(method(GET), url_path('/users'), 'list_users');
        route(method(POST), url_path('/users'), 'create_user');
    });
});

use PhpCompatible\Router\ServerRequest;
use PhpCompatible\Router\JsonResponse;

router(function() {
    route(method(GET), url_path('/api/users/:id'), function() {
        $request = new ServerRequest();
        $id = $request->getRouteParam(':id');

        return JsonResponse::ok(array('id' => $id, 'name' => 'John'));
    });
});

route(method(GET), url_path('/resource'), $handler);
route(method(POST), url_path('/resource'), $handler);
route(method(PUT), url_path('/resource/:id'), $handler);
route(method(DELETE), url_path('/resource/:id'), $handler);
route(method(PATCH), url_path('/resource/:id'), $handler);

route(method(GET), url_path_params('/users/:id'), function() {
    $id = $_GET[':id'];
});

route(method(GET), url_path_params('/posts/:postId/comments/:commentId'), function() {
    $postId = $_GET[':postId'];
    $commentId = $_GET[':commentId'];
});

routerGroup('/admin', function() {
    route(method(GET), url_path('/dashboard'), 'admin_dashboard');
    route(method(GET), url_path('/users'), 'admin_users');
});
// Matches: /admin/dashboard, /admin/users

middleware(function() {
    // Return false to stop route processing
    if (!check_auth()) {
        http_response_code(401);
        return false;
    }
    return true;
});

// JSON responses
echo json_response(HTTP_OK, array('data' => $data));
echo json_response(HTTP_CREATED, array('id' => $newId));
echo json_response(HTTP_BAD_REQUEST, array('error' => 'Invalid input'));

// HTML responses
echo html_response(HTTP_OK, '<h1>Hello World</h1>');

// Plain text
echo text_response(HTTP_OK, 'Plain text response');

use PhpCompatible\Router\ServerRequest;
use PhpCompatible\Router\JsonResponse;
use PhpCompatible\Router\HtmlResponse;

// Request object
$request = new ServerRequest();
$request->getMethod();           // GET, POST, etc.
$request->getUri();              // /users/123
$request->getQueryParams();      // $_GET
$request->getRouteParam(':id');  // URL parameters

// JSON Response
$response = JsonResponse::ok(array('status' => 'success'));
$response = JsonResponse::created(array('id' => 1));
$response = JsonResponse::badRequest(array('error' => 'Invalid'));
$response = JsonResponse::notFound(array('error' => 'Not found'));

// HTML Response
$response = HtmlResponse::view('/path/to/template.php', array('name' => 'John'));

HTTP_OK                  // 200
HTTP_CREATED             // 201
HTTP_NO_CONTENT          // 204
HTTP_BAD_REQUEST         // 400
HTTP_UNAUTHORIZED        // 401
HTTP_FORBIDDEN           // 403
HTTP_NOT_FOUND           // 404
HTTP_INTERNAL_SERVER_ERROR // 500
// ... and many more

use PhpCompatible\Router\HttpException;

// Throw exceptions that automatically set status codes
throw HttpException::badRequest('Invalid input');
throw HttpException::unauthorized('Please log in');
throw HttpException::forbidden('Access denied');
throw HttpException::notFound('Resource not found');
throw HttpException::internalServerError('Something went wrong');

// Closure
route(method(GET), url_path('/'), function() {
    echo 'Hello';
});

// Function name
route(method(GET), url_path('/about'), 'show_about_page');

// Static method
route(method(GET), url_path('/contact'), 'ContactController::show');

// Array callable
route(method(GET), url_path('/help'), array($controller, 'help'));
bash
composer 
nginx
location / {
    try_files $uri $uri/ /index.php?url=$uri&$args;
}