PHP code example of needinfo / router

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

    

needinfo / router example snippets




use Needinfo\Router\Router;

$router = new Router("https://www.youdomain.com");

/**
 * The controller must be in the namespace App\Controllers
 */
$router->namespace("App\\Controllers");

$router->get("/", "Web:home");
// Default parameters catch anything [^/]+
$router->post("/route/{id}", "Web:method");

// You can use Regex Constraints (v2.0+) 
$router->get("/users/{id:\d+}", "Web:user"); // id only matches Numbers!
$router->get("/posts/{slug:[a-z\-]+}", "Web:post"); // slug only matches lowercase and hyphens!

/**
 * Group by routes and namespace
 * The controller must be in the namespace App\Controllers\Admin
 */
$router->group("admin")->namespace("App\\Controllers\\Admin");

$router->get("/route", "Dashboard:home");

/**
 * This method executes the routes directly based on $_SERVER
 */
$router->dispatch();

/*
 * Redirect all errors
 */
if ($router->error()) {
    $router->redirect("/error/{$router->error()}"); // e.g., 404 or 405
}

$route = $router->get("/dashboard", "Web:dashboard")
                ->name("admin.dashboard")
                ->middleware("RequireAuth")
                ->with(["role" => "admin"]);

$router->setContainer($myContainer);
$router->dispatch();

$router->get("/api/user", function($request, $params) {
    echo $request->getBody(); // $request é o contexto customizado repassado
});

$router->dispatch($request);

$match = $router->match('POST', '/api/users');

if ($match->isSuccess()) {
    $matchedRoute = $match->getRoute();
    $params = $match->getParams();
    
    // Voce assume o controle da execução:
    // (new $matchedRoute->getHandler())($params);
} elseif ($match->getError() === 405) {
    echo "Metodos aceitos: " . implode(', ', $match->getAllowedMethods());
} else {
    echo "404 Not Found";
}
nginx
location / {
    if ($script_filename !~ "-f"){
        rewrite ^(.*)$ /index.php?route=/$1 break;
    }
}