簡體   English   中英

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'; 從示例代碼。 但顯示以下錯誤。

致命錯誤:未捕獲的錯誤:在 C:\\wamp\\www\\testproj\\includes\\FastRoute\\src\\functions.php:21 中找不到類 'FastRoute\\RouteCollector' 堆棧跟蹤:#0 C:\\wamp\\www\\testproj\\includes \\routing.php(13): FastRoute\\simpleDispatcher(Object(Closure)) #1 C:\\wamp\\www\\testproj\\index.php(9): require_once('C:\\wamp\\www\\testp...' ) #2 {main} 在第 21 行的 C:\\wamp\\www\\testproj\\includes\\FastRoute\\src\\functions.php 中拋出

我想我在設置上做錯了。 但是我仍然找不到適合初學者的更好的樣本。 所以,請指出我哪里做錯了。 提前致謝。

請閱讀有關PHP 自動加載的信息

您的問題在於刪除該行

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

這個 PHP 腳本安裝了一個自動加載器,當某些需要的 PHP 類未知時,它會自動加載必要的 PHP 腳本文件。

如果您出於某種原因不想要此自動加載器,則必須通過其他方式加載所需的類。 通常這是通過在每個 PHP 腳本中添加行來完成的

require 'FastRoute/RouteCollector.php';
require 'FastRoute/Dispatcher.php';
...

所以,大多數時候你確實想要這個自動加載器,因為它讓生活更輕松,代碼更短。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM