PHP code example of viloveul / router

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

    

viloveul / router example snippets




// init collection object
$collection = new Viloveul\Router\Collection();

// declare class controller for handler
class MyController
{
	public function look($name)
	{
		return $name;
	}
}

// declare hello handler from my controller
$helloRoute = new Viloveul\Router\Route('GET /hello/:name', [MyController::class, 'look']);
// or 
// $helloRoute = new Viloveul\Router\Route('GET /hello/:name', [MyController::class, 'look']);
// add foo to collection
$collection->add($helloRoute);

// declare foo handler
$fooRoute = new Viloveul\Router\Route('GET /foo/{:bar}', function($bar) {
	return $bar;
});
// add foo to collection
$collection->add($fooRoute);

// declare test handler
$testRoute = new Viloveul\Router\Route('/test/:name', [
	'method' => 'GET|POST|PUT|PATCH',
	'handler' => function ($name) {
		return $name;
	}
]);
// add test to collection
$collection->add($testRoute);

// init object dispatcher with collection
$router = new Viloveul\Router\Dispatcher($collection);

// in action

$router->dispatch('GET', Zend\Diactoros\UriFactory::createUri('/hello/zafex'));
$route1 = $router->routed();

$router->dispatch('GET', Zend\Diactoros\UriFactory::createUri('/foo/hello-world'));
$route2 = $router->routed();

$router->dispatch('GET', Zend\Diactoros\UriFactory::createUri('/test/fajrul-akbar-zuhdi'));
$route3 = $router->routed();

var_dump($route1, $route2, $route3);