2015-10-11 107 views
0

我是PHP的新手。我正在使用packagist.org的聯盟/路由在我的應用程序中進行路由,並且在我的根目錄中有一個公用文件夾,其中有一個index.php文件用於路由,如下所示。htaccess自定義url路由使用php路由

require_once '../vendor/autoload.php'; 

use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 

$router = new League\Route\RouteCollection; 

$router->addRoute('GET', '/acme', function (Request $request, Response $response) { 
    echo "here"; 

    return "working"; 
}); 

$dispatcher = $router->getDispatcher(); 

$response = $dispatcher->dispatch('GET', '/acme'); 

$response->send(); 

.htaccess文件,如果在根文件夾,如下面

RewriteEngine On 

RewriteBase /HMT/public 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule^index.php [QSA,L] 

問題是,當我運行顯示http://localhost/HMT/acme什麼。我試着在public/index.php文件的每一行後面添加一個echo語句,並注意到下面的行是不起作用的。我也認爲我的.htaccess可能是問題?

$dispatcher = $router->getDispatcher(); 

感謝您的幫助,謝謝。

+0

您應該會收到一條錯誤消息。嘗試在索引文件的開頭添加以下內容:ini_set('display_errors',1);'用於調試目的。 – nebulousGirl

回答

3

所以這裏有幾個問題。

看起來您好像關閉了錯誤報告,或者您會看到某種錯誤。

將以下代碼添加到index.php的頂部。

error_reporting(-1); 
ini_set('display_errors', 'On'); 

.htaccess實際上應該是在你的public目錄併爲下面的格式。

RewriteEngine On 
RewriteBase /HMT/public 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond $1 !\.(html) 
RewriteRule ^(.*)$ index.php?/$1 [L,QSA] 

然後根據你給了,如果你訪問http://localhost/HMT/public則應全部正常工作的信息。

根據您可能收到的任何錯誤和您正在使用的league/route的版本,可能還有一步要確保將請求URI正確發送到調度程序。

+0

謝謝。如果我訪問「/ acme」,出現錯誤「內部服務器錯誤」,當我訪問「/」時出現錯誤「Catchable致命錯誤:傳遞給League \ Route \ RouteCollection :: getDispatcher()的參數1必須是Psr \ Http \ Message \ ServerRequestInterface實例,沒有給出。「 – Erick

+0

沒錯,這是因爲你的index.php文件設置爲使用版本1的聯盟/路線,但實際上你已經安裝了未完成的版本2 – philipobenito