How do I use FastRoute?

user4912666 picture user4912666 · Jul 31, 2016 · Viewed 13.5k times · Source

I'm attempting to use the FastRoute routing library and can't get the simple usage example to work.

Here is the basic usage example found on the GitHub page:

<?php

require '/path/to/vendor/autoload.php';

$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
    $r->addRoute('GET', '/users', 'get_all_users_handler');
    // {id} must be a number (\d+)
    $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler');
    // The /{title} suffix is optional
    $r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler');
});

// Fetch method and URI from somewhere
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];

// Strip query string (?foo=bar) and decode URI
if (false !== $pos = strpos($uri, '?')) {
    $uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);

$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
    case FastRoute\Dispatcher::NOT_FOUND:
        // ... 404 Not Found
        break;
    case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        $allowedMethods = $routeInfo[1];
        // ... 405 Method Not Allowed
        break;
    case FastRoute\Dispatcher::FOUND:
        $handler = $routeInfo[1];
        $vars = $routeInfo[2];
        // ... call $handler with $vars
        break;
}

Where the comment reads "... call $handler with $vars", I've tried returning call_user_func_array($handler, $vars) but it doesn't work.

I also thought that maybe it was the .htaccess file that was stopping it working, as the Github page doesn't have a .htaccess file example for the project. I'm using this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [QSA,L]

I've also tried calling a route with a closure as the handler, like so:

$r->addRoute('GET', '/', function() {
    echo 'home';
});

Answer

Izhari Ishak Aksa picture Izhari Ishak Aksa · Aug 30, 2016

Example how to handle request

$r->addRoute('GET', '/users', 'User/getUsers');

Then if dispatcher found, you can process it like 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.