2016-08-05 60 views
0

使用Laravel 5.2,並使用中間件,我需要從請求的URI中刪除某個部分,然後才能分派它。更具體地說,在像「http://somewebsite.com/en/company/about」這樣的url中,我想從中刪除「/ en /」部分。

這是我做的方式:

... 

class LanguageMiddleware 
{ 
    public function handle($request, Closure $next) 
    { 

     //echo("ORIGINAL PATH: " . $request->path()); //notice this line 


     //duplicate the request 
     $dupRequest = $request->duplicate(); 

     //get the language part 
     $lang = $dupRequest->segment(1); 

     //set the lang in the session 
     $_SESSION['lang'] = $lang; 

     //now remove the language part from the URI 
     $newpath = str_replace($lang, '', $dupRequest->path()); 

     //set the new URI 
     $request->server->set('REQUEST_URI', $newpath); 


     echo("FINAL PATH: " . $request->path()); 
     echo("LANGUAGE: " . $lang); 


     $response = $next($request); 
     return $response; 

    }//end function 

}//end class 

此代碼工作正常 - 當原始URI是「恩/公司/約」,所產生的URI的確是「公司/約」。我的問題是這樣的:注意到我回應原始路徑的那一行被評論(第8行)。這是有目的地完成的。如果我取消註釋該行,則代碼不起作用;當原始URI是「en/company/about」時,生成的URI仍然是「en/company/about」。

我只能從這裏得出兩個結論:在操縱請求之前發送輸出是某種方式的罪魁禍首(測試 - 事實並非如此),或者調用$ request-> path()方法來獲取URI與此有關的事情。雖然在製作過程中,我絕對不需要回顯URI,雖然這僅用於調試目的,但我仍然需要知道爲什麼會發生這種情況。我只想獲取請求的URI。我在這裏錯過了什麼?

旁註:該代碼與源於第一回答這個帖子: https://laracasts.com/discuss/channels/general-discussion/l5-whats-the-proper-way-to-create-new-request-in-middleware?page=1

回答

0

我不認爲線#8操縱你的輸出。
這裏是laravel's codepath()方法:

public function path() 
    { 
     $pattern = trim($this->getPathInfo(), '/'); 
     return $pattern == '' ? '/' : $pattern; 
    } 

正如你可以看到它是剛剛提取pathInfo無需編輯請求本身。

+0

我知道,這就是爲什麼這對我來說似乎很尷尬。那麼怎麼會這樣呢,當這條代碼被評論時,代碼完美地工作,但是當代碼沒有工作時它不工作? – pazof

+0

我會嘗試對我的設置做同樣的事情,並會讓你知道 – jaysingkar