PHP code example of morphable / simple-routing

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

    

morphable / simple-routing example snippets




Morphable\SimpleRouting;
use \Morphable\SimpleRouting\Route;

/*
$req = \Morphable\SimpleRouting\Request
$res = \Morphable\SimpleRouting\Response
*/

// A simple route with response
$route = new Route('GET', '/user/:user_id/', function ($req, $res) {
    return $res->sendResponse('UserId = ' . $req->getParam('user_id'), 200);
});

// A POST route with middleware
$route2 = new Route('POST', '/user/:user_id/update', function ($req, $res) {
    return $res->sendResponse('Welcome user 2!');
}, [
    // middlewares
    function ($req, $res) {
        if ($req->getParam('user_id') != 2) {
            return $res->sendResponse('Forbidden', 403);
        }
    }
]);

SimpleRouting::add('user_detail', $route);
SimpleRouting::add('user_update', $route2);

try {
    SimpleRouting::execute();
} catch (\Morphable\SimpleRouting\Exception\RouteNotFound  $e) {
    // catch 404
    die('404');
}



use \Morphable\SimpleRouting\Builder;

$route = (new Builder())
        ->setMethod('GET')
        ->setRoute('/user/:userId')
        ->setCallback($callback)
        ->setMiddleware([$callback])
        ->build();

$route = Builder::fromArray([
    'method' => 'GET',
    'route' => '/user/:userId',
    'callback' => $callback,
    'middleware' => $callback
]);