PHP code example of fastero / php-router

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

    

fastero / php-router example snippets


$routes = [
    'admin' => Literal::config('admin')
        ->setController(MyProject\Admin\IndexController::class, 'run')
        ->get(),
    'admin-user-list' => Section::config('admin/user', '[/age/:from/:to][/country/:country]')
        ->setController(MyProject\Admin\UserController::class, 'run')
        ->get(),
    'admin-user-id' => Section::config('admin/user', '/:id')
        ->parameter('id', null, '[0-9]')
        ->setController(MyProject\Admin\UserIdController::class, 'run')
        ->get(),

    'admin-user-name' => Section::config('admin/user', '/:name')
        ->setController(MyProject\Admin\UserNameController::class, 'run')
        ->get(),
];

$router = new Router($routes);

try{

    $data = $router->match($_SERVER['REQUEST_METHOD'], trim($_SERVER['REQUEST_URI'],'/'),$_GET);
    $roteName = $data['name']; //name of route that match
    $routeParameters = $data['parameters']; //parameters that were extracted
    $query = $data['query']; //query parameters (usually they are the same as were passed it a ->match method
    $controller = $data['options']['controller']; //['class'=> 'className', 'method' => 'methodName']
    //create controller and call it's method?
} catch (\Fastero\Router\Exception\RouterNotFoundException $exception){
    //do something if matching route was not found (display 404)
} catch (Exception $exception){
    //do something if there was an error during matching process (display 503 ?)
}

$router->makePath('admin-user-name', ['name' => 'nobody']) // will return string "admin/user/nobody"


$routes = [
 'route-name' => Section::config('user/', 'id/:user_id')
         ->parameter('user_id', null, '[0-9]+')
         ->setController('controllerClassName', 'Method')
         ->get(),
];

->setController($class, $method)

->setReversePattern($pattern)

setReverseGenerator($generatorClass)

-> queryParameter($name, $
$pattern

php->parameter($name, $default = null, $validationRule = null)
user/age(?<age>([0-9])+)