PHP code example of puz / router

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

    

puz / router example snippets



use \Puz\Router\Router;

$router = new Router;


// ...
// Adding a new one
Router::registerValidator(MyValidatorClass::class);

// Replacing the list and then add a new one
Router::registerValidator(MyValidatorClass::class, true);


// ...
$router = new Router;
$router->get("/optional-url", optionalCallback())->...;
$router->head("/optional-url", optionalCallback())->...;
$router->post("/optional-url", optionalCallback())->...;
$router->put("/optional-url", optionalCallback())->...;
$router->patch("/optional-url", optionalCallback())->...;
$router->delete("/optional-url", optionalCallback())->...;


// ...
$router->method("get", "post")->...
$router->method(["get", "post"])->...


// ...
$route = $router->method("get")->url("/hello-world", optionalCallback())->...


// ...
$router->post("/support")->callback(function() {
    // Send email to support
});

// You can create parameters by using ":" followed by letters a-z
$router->get("/hello-:name", function ($name) {
    echo "Hello, $name";
});


// ...
$router->run([
    'method' => $_SERVER['REQUEST_METHOD'],
    'url' => $_SERVER['REQUEST_URI']
]);


// ...
// Ugly code to remove the subfolders.
// Got a cleaner and more understandable way? Give me a ping
$url = explode("/".trim(str_replace($_SERVER['DOCUMENT_ROOT'], "", dirname($_SERVER['SCRIPT_FILENAME'])), "/"), $_SERVER['REQUEST_URI'], 2)[1];

$router->run([
    'method' => $_SERVER['REQUEST_METHOD'],
    'url' => $url
]);