PHP7 的路由库

Routing Lib for PHP7

我需要为 php 使用路由插件,我决定使用 nikic/FastRoute [https://github.com/nikic/FastRoute]。但是,由于我对 php 的了解有限,我仍然无法成功使用它。

这是我的代码。

require_once 'FastRoute/src/functions.php';
# create a stack of actions

$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
    $r->addRoute('GET', '/', 'get_all_users_handler');
    // {id} must be a number (\d+)
    $r->addRoute('GET', '/contract-management', '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;
}

function get_user_handler(){
    print_r("here");
}

function get_article_handler(){
    print_r("article handler");
}

我刚刚更改了 require '/path/to/vendor/autoload.php';至 require_once 'FastRoute/src/functions.php';从示例代码。但是显示以下错误。

致命错误:未捕获错误:Class 'FastRoute\RouteCollector' 在 C:\wamp\www\testproj\includes\FastRoute\src\functions 中找不到。php:21 堆栈跟踪:#0 C:\wamp\www\testproj\includes\routing.php(13): FastRoute\simpleDispatcher(对象(闭包)) #1 C:\wamp\www\testproj\index.php(9): require_once('C:\wamp\www\testp...') #2 {main} throw in C:\wamp\www\testproj\includes\FastRoute\src\functions.php on line 21

我觉得我的设置有问题。但是我仍然找不到适合初学者的更好示例。所以,请指出我哪里做错了。提前致谢。

请阅读 PHP autoload

您的问题在于删除行

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

此 PHP 脚本安装一个自动加载器,它会自动加载必要的 PHP 脚本文件,当某些需要时 PHP class 未知。

如果您出于某种原因不需要此自动加载器,则必须通过其他方式加载所需的 classes。通常这是通过在每个 PHP 脚本

中添加像 这样的行来完成的
require 'FastRoute/RouteCollector.php';
require 'FastRoute/Dispatcher.php';
...

所以,大多数时候你确实需要这个自动加载器,因为它让生活更轻松,代码更短。