PHP code example of semperton / routing

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

    

semperton / routing example snippets


use Semperton\Routing\Collection\RouteCollection;

$routes = new RouteCollection();

$routes->map(['GET', 'POST'], '/blog/article/:id:d', 'article-handler');
$routes->get('/category/product', 'product-handler');
$routes->post('/user/login', 'login-handler');

// grouping

$routes->group('/blog', function (RouteCollection $blog) {
	$blog->get('/article', 'article-handler');
	$blog->get('/category', 'category-handler');
});

use Semperton\Routing\Matcher\RouteMatcher;

$matcher = new RouteMatcher($routes);

$result = $matcher->match('GET', '/blog/article/3');

$result->isMatch(); // true
$result->getHandler(); // 'article-handler'
$result->getParams(); // ['id' => '3']

$routes->get('/*path', 'admin-handler');
$result = $matcher->match('GET', '/admin/users');
$result->getParams(); // ['path' => 'admin/users']

use Semperton\Routing\Collection\RouteCollection;
use Semperton\Routing\Matcher\RouteMatcher;

$routes = new RouteCollection();
$routes->get('/media/:filename:file', 'handler');

$matcher = new RouteMatcher($routes);
$matcher->setValidator('file', function (string $value) {

	$parts = explode('.', $value, 2);

	if(isset($parts[1])){
		return true;
	}

	return false;
});

$matcher->validate('readme.txt', 'file'); // true

$result = $matcher->match('GET', '/media/data.json');
$result->getParams(); // ['filename' => 'data.json']

use Semperton\Routing\Collection\RouteCollection;

$routes = new RouteCollection();

// add a named route
$routes->get('/product/:id:d', 'product-route');

// build it
$routes->reverse('product-route', ['id' => 42]); // '/product/42'