PHP code example of aniruddh / phprouter

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

    

aniruddh / phprouter example snippets



use Aniruddh\Router\Router;
$router = new Router();
// default method is GET does not nction() {
    echo 'get test1';
});

$router->add('/test', function() {
    echo 'post test';
});

//you can specify if you want
$router->add('/test1', function() {
    echo 'get test1';
    
}, ['GET']);

//Except GET you have to specify the method
$router->add('/test1', function() {
    echo 'post test1';
}, ['POST']);

//you can specify multiple method
$router->add('/test2', function() {
    echo 'get and post test2';
}, ['GET', 'POST']);

//set 404 if not default 404 page shown
$router->set404(function(){
    echo "<h1>404 not found! </h1> url: " . htmlentities($_SERVER['REQUEST_URI']);
});
//run the router
$router->run();

//method and middleware must be an array
$route->add($route, $callback, $method, $middleware);

//router use regex for route matching
// Matches /users/42, but not /users/abc
$router->add('/users/\d+', 'callback');

// Example with middleware
$route->add('/users/\d+', 'callback', ['GET'], ['before'=> callabck, 'after'=> callback]);

//Example with class object and method
$router->('/users', ['classname','method']);

//Example with trailing slash option enable
 Router(true, 1); //default is false and 0 // 0 means without trailing slash
// default method is GET does not h version will work