Build routes for a small project

materix
Member | 65
+
0
-

I need to setup a couple of routes for a small and simple project.

GET /route1
POST /route2
GET|POST /route3

Is it possible to setup routes with Nette packages without installing the whole nette-application/framework?

materix
Member | 65
+
0
-

I have already seen that page.

As I understand nette/routing only does route-matching. But I would still need something for dispatching?

materix
Member | 65
+
0
-

Does not anyone use nette/routing as standalone package? :-)

Mistrfilda
Member | 76
+
+3
-

I havent used it standalone, but there is a section in documentation about it https://doc.nette.org/…tion/routing#…

Marek Bartoš
Nette Blogger | 1146
+
+2
-

It does only route matching. For dispatching you have to add an parameter to each route and based on this parameter decide yourself what to do. It can look like this:

$router = new RouteList();
$router->addRoute('/path', [
	'controller' => function(): void {
		// Do something
		echo 'response';
	},
]);

$httpRequest = (new Nette\Http\RequestFactory)->fromGlobals();
$parameters = $router->match($httpRequest);
if ($parameters === null) {
	// no match, 404
	exit();
}

$controller = $parameters['controller'] ?? null;
if($controller === null) {
	throw new \Exception('each route has to define controller');
}

$controller();
exit();

Parameter controller is a callback executed when route is matched. You just have to make sure each route has this parameter. And never add it to url (like $router->addRoute('/path/<controller>',) – this parameter is definitely not safe to be changed by user.

Last edited by Marek Bartoš (2021-10-25 15:54)

materix
Member | 65
+
0
-

Thank you for the awesome reply! This was exactly what I was searching for.

For reference, in line 16 $parameters is written as $params.