PHP code example of zkrati / router

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

    

zkrati / router example snippets


$router = new Zkrati\Routing\SimpleRouter();

$router->get("/test", function() {
    // handle GET request at /test
});

$router->post("/test", function() {
    // handle POST request at /test
});

$router->run();

$router->get("/test/path", "Class:methodName");
// this code will create an instance of Class and call it's method methodName

$router->get("/test/path", "Namespace\Class:methodName");
// if you are using namespaces

$instance = new Class();
$router->get("/testuju/path", array($instance, "methodName"));
// this code will use the given instance of Class and call it's method methodName

$router->get("/test/<variable>/<next_variable>/path", function($variables) {
    // variables <variable> and <next_variable> are available in array $variables by it's keys
    // for example with url /test/example/showcase/path
    
    echo $variables["variable"];      // will output "example"
    echo $variables["next_variable"]; // will output "showcase"
});


$router->get("/test/<variable>/<next_variable>/path", function($variables, $params) {
    // for url /test/example/showcase/path?optional=true&param=john will passed array $params look like:
    // array(2) {
    //     ["optional"] => string(4) "true"
    //     ["param"] => string(4) "john"
    //   }
});


$router->get("/test/path/*", "Class:methodName");
// this code will match all paths starting /test/path/ for example:
//  - /test/path/first
//  - /test/path/second
//  - /test/path/every/other/path

$router->option("*", "Class:methodName");
// This will handle all option requests

$router->get("/test/<variable>/*", "Class:methodName");

$router->get("/test/<variable>/<next_variable>/path", function($variables, $params, $headers) {
    // variable $headers is array which contains all request headers 
});


try{

    $router->get("/test/", "Class:firstMethod");
    $router->get("/other/route", "Class:secondMethod");
    $router->get("/cool/route", "invalid handler");
    
} catch(InvalidHandlerException $e) {
    echo $e->getMessage();
}

try{
    $router->run();
} catch(RouteNotFoundException $e) {
    echo $e->getMessage();
}

$router->setInstantiator($instantiator, "getInstance");
// where $instantiator is your custom instantiator and "getInstance" is name of it´s method to get instance