我如何使用FastRoute?

时间:2016-07-31 17:43:38

标签: php url-routing

我正在尝试使用FastRoute路由库,无法使用简单的用法示例!我想知道我是否因此而迟钝,因为它应该非常简单。

以下是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;
}

如果评论内容为“...使用$ vars调用$ handler”,我已尝试返回call_user_func_array($handler, $vars),但它不起作用。

我还认为可能是 .htaccess 文件阻止它正常工作,因为Github页面没有项目的 .htaccess 文件示例。我正在使用这个:

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

我也试过调用一个带闭包的路由作为处理程序,如下所示:

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

但没有!我现在变得很沮丧......

4 个答案:

答案 0 :(得分:16)

如何处理请求的示例

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

然后,如果发现调度程序,您可以按照

进行处理
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;

不要忘记使用User方法创建课程getUsers()

答案 1 :(得分:2)

我制作了一个演示API,该API使用FastRoute和PHP-DI(依赖注入)来展示如何同时使用两者。请参阅:https://github.com/tochix/shapes-api/blob/master/src/Service/Http/Router.php#L94。简而言之,它看起来像这样:

/**
 * @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;
    }
}

答案 2 :(得分:1)

$r->addRoute(['GET','POST','PUT'], '/test', 'TestClass/testMethod');

然后在你的调度方法中:

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

类和方法当然可以通过call_user_func()调用,但是因为我希望路由器更抽象并放在根目录之外我决定使用DI容器,这很棒。

答案 3 :(得分:0)

创建方法homepage()

使用方法 users() 创建类 User

添加如下路线

$r->addRoute(['GET','POST','PUT'], '/home',  'homepage');
$r->addRoute(['GET','POST','PUT'], '/aboutus', function() { echo 'About us'; });
$r->addRoute(['GET','POST','PUT'], '/users', 'User/users');

如果找到调度员

case FastRoute\Dispatcher::FOUND:
    $handler = $routeInfo[1];
    $vars    = $routeInfo[2];
    if ( is_object( $handler ) || ( is_string( $handler ) && strpos( $handler, '/' ) === false ) ) {
        if(count($vars) > 0) {
            call_user_func_array($handler,$vars);
        } else {
            call_user_func_array($handler,array());
        }
    } else if ( is_string( $handler ) && strpos( $handler, '/' ) !== false ) {
        list($class, $method) = explode( '/', $handler, 2 );
        if ( class_exists( $class ) && method_exists( $class, $method ) ) {
            call_user_func_array( array( new $class(), $method ), $vars );
        }
    }
    break;

那么,

/home 将调用方法 homepage()

/aboutus 将在添加路由

处调用给定的函数对象

/users 将从 User

调用 users() 方法