2016-10-06 105 views
-2

我需要使用php的路由插件,並且我決定使用nikic/FastRoute [https://github.com/nikic/FastRoute]。但是,由於我對PHP的知識有限,我仍然無法成功使用它。PHP7的路由庫

這是我的代碼。

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

我只是改變需要 '/path/to/vendor/autoload.php'; require_once'FastRoute/src/functions.php';從示例代碼。但顯示下面的錯誤。

致命錯誤:未捕獲錯誤:在C:\ wamp \ www \ testproj \ includes \ FastRoute \ src \ functions.php中找不到類'FastRoute \ RouteCollector':21 Stack trace:#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 ...')第21行拋出的C:\ wamp \ www \ testproj \ includes \ FastRoute \ src \ functions.php#2 {main}

我認爲我在設置時做了錯誤。但我仍然無法爲初學者找到更好的樣本。所以,請指出我在哪裏做錯了。提前致謝。

+2

您已經提到過您的錯誤:「我剛剛更改了require'/path/to/vendor/autoload.php'; require_once'FastRoute/src/functions.php';來自示例代碼。」搜索PHP作曲家和自動加載。 –

+0

感謝Olaf Dietsche。我沒有意識到這個作曲家或自動加載有如此多的影響。但我仍然有一個問題。我不能只是不安裝這個PHP作曲家來使用這種類型的庫?有沒有自定義的方式來加載庫而不安裝composer?我不想在每臺實時服務器和本地服務器上安裝這個,只是爲了使用這一個lib。或者我沒有選擇? –

+0

當您以某種方式更改程序,然後停止工作時,只要恢復您的更改並查看它是否可以解決問題。然後,您可以查看相關代碼並嘗試瞭解代碼(或缺少代碼)如何影響您的程序。 –

回答

1

請閱讀關於PHP autoload

你的問題就在於消除線

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

這個PHP腳本安裝自動加載磁帶機,自動加載必要的PHP腳本文件,當一些必要的PHP類是未知的。

如果您因某種原因不想使用此自動加載器,則必須通過其他方式加載所需的類。通常,這是通過將線在每個PHP腳本

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

所以做這樣,你最需要這麼做自動加載磁帶機,因爲它讓生活變得更輕鬆和代碼的時間越短。