PHP code example of sugatasei / bredala-router

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

    

sugatasei / bredala-router example snippets


// $method absent -> CallableRoute, $controller est utilisé comme callable
$router->get('/ping', fn() => 'pong');
$router->get('/ping', [$service, 'method']);

// $method présent -> ControllerRoute, instanciée au moment de l'exécution
$router->get('/user/{id}', UserController::class, 'show');

$router->wildcard('slug', '([a-z0-9-]+)');
$router->get('/p/{slug}', PostController::class, 'show');

$uri = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);

$router->get('/{any}/{id}', PostController::class, 'show');
// GET /post/7 -> show('post', '7')

$router->get('/files/{all}', FileController::class, 'serve');
// GET /files/a/b/c -> serve('a', 'b', 'c')

public function serve(string ...$segments): string
{
    return implode('/', $segments);
}

$router->get('/user/{id}', [new UserController($repository), 'show']);

use Bredala\Router\Router;
use Bredala\Router\RouteException;

$router = new Router();

$router->wildcard('slug', '([a-z0-9-]+)');

$router->get('/', HomeController::class, 'index');
$router->get('/user/{id}', UserController::class, 'show');
$router->post('/user', UserController::class, 'store');
$router->get('/p/{slug}', PostController::class, 'show');
$router->get('/files/{all}', FileController::class, 'serve');

$method = $_SERVER['REQUEST_METHOD'] ?? '';
$uri = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);

try {
    echo $router->run($method, $uri)->execute();
} catch (RouteException) {
    http_response_code(404);
    echo 'Not found';
}