PHP code example of slince / routing

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

    

slince / routing example snippets


$routes = new Slince\Routing\RouteCollection();
$routes->get('/products', 'Products::index')->setName('product_index');

$request = Zend\Diactoros\ServerRequestFactory::fromGlobals(); //Creates the psr7 request instance

$matcher = new Slince\Routing\Matcher($routes);
$generator = new Slince\Routing\Generator($request);

$route = $matcher->matchRequest($request); //Matches the current request
var_dump($route->getComputedParamters()); //Dumps route computed paramters
echo $generator->generate($route); //Generates path 

$route = $routes->getByAction('Products::index');
echo $generator->generate($route); //Generates path 

$route = $routes->getByName('product_index');
echo $generator->generate($route); //Generates path 

$routes = new Slince\Routing\RouteCollection();
$route = new Slince\Routing\Route('/products/{id}', 'Products::view');
$routes->add($route);

$route->setRequirements([
    'id' => '\d+'
]);

$route->setDefaults([
    'id' => 1
]);

$routes = new RouteCollection();

$routes->get('/pattern', 'action');
$routes->post('/pattern', 'action');
$routes->put('/pattern', 'action');
$routes->delete('/pattern', 'action');
$routes->options('/pattern', 'action');
$routes->patch('/pattern', 'action');

$route->setMethods(['GET', 'POST', 'PUT']);

$routes->create('/products', 'Products::index')
    ->setHost('product.domain.com');

$routes = new Slince\Routing\RouteCollection();

$routes->https('/pattern', 'action');
$routes->http('/pattern', 'action');

$route->setSchemes(['http', 'https']);

$routes = new Slince\Routing\RouteCollection();
$routes->create('/products/{id}.{_format}', 'Products::view');
$matcher = new Slince\Routing\Matcher($routes);

try {
    $route = $matcher->match('/products/10.html');
    
    print_r($route->getComputedParameters())// ['id' => 10, '_format' => 'html']
    
} catch (Slince\Routing\Exception\RouteNotFoundException $e) {
    //404
}

$request = Zend\Diactoros\ServerRequestFactory::fromGlobals();
try {
    $route = $matcher->matchRequest($request);
} catch (Slince\Routing\Exception\MethodNotAllowedException $e) {
    //403
    var_dump($e->getAllowedMethods());
} catch (Slince\Routing\Exception\RouteNotFoundException $e) {
    //404
}

$generator = new Slince\Routing\Generator();

$route = new Slince\Routing\Route('/foo/{id}', 'action');
echo $generator->generate($route, ['id' => 10]); //will output "/foo/10"

$request = Zend\Diactoros\ServerRequestFactory::fromGlobals();
$generator->setRequest($request);

echo $generator->generate($route, ['id' => 10], true); //will output "{scheme}://{domain}/foo/10"