How do I use FastRoute?

一个人想着一个人 提交于 2021-02-05 20:27:54

问题


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';
});

回答1:


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.




回答2:


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;
    }
}



回答3:


$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 = $routeInfor[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.



来源:https://stackoverflow.com/questions/38686776/how-do-i-use-fastroute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!