How do I use FastRoute?
$r->addRoute(['GET','POST','PUT'], '/test', 'TestClass/testMethod');
Then in your dispatch method:
$routeInfo = $router->dispatch($httpMethod, $uri)
switch($routeInfo[0]) {
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
list($class, $method) = explode('/',$handler,2);
$controller = $container->build()->get($class);
$controller->{$method}(...array_values($vars));
break;
}
Class and method of course could be invoked by call_user_func(), but as I wanted the router to be more abstract and placed outside in the root directory I decided to use DI container, which is brilliant.
Example how to handle request
$r->addRoute('GET', '/users', User::class . '/getUsers');
Then if dispatcher found, you can process it as following
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
list($class, $method) = explode("/", $handler, 2);
call_user_func_array(array(new $class, $method), $vars);
break;
Don't forget to create class User
with getUsers()
method.
I made a demo API that uses FastRoute and PHP-DI(dependency injection) to showcase how to use both. See: https://github.com/tochix/shapes-api/blob/master/src/Service/Http/Router.php#L94. In a nutshell, it looks like this:
/**
* @param string $requestMethod
* @param string $requestUri
* @param Dispatcher $dispatcher
* @throws DependencyException
* @throws NotFoundException
*/
private function dispatch(string $requestMethod, string $requestUri, Dispatcher $dispatcher)
{
$routeInfo = $dispatcher->dispatch($requestMethod, $requestUri);
switch ($routeInfo[0]) {
case Dispatcher::NOT_FOUND:
$this->getRequest()->sendNotFoundHeader();
break;
case Dispatcher::METHOD_NOT_ALLOWED:
$this->getRequest()->sendMethodNotAllowedHeader();
break;
case Dispatcher::FOUND:
list($state, $handler, $vars) = $routeInfo;
list($class, $method) = explode(static::HANDLER_DELIMITER, $handler, 2);
$controller = $this->getContainer()->get($class);
$controller->{$method}(...array_values($vars));
unset($state);
break;
}
}