2014-11-14 90 views
2

我正在寫一個Laravel應用程序,它基本上允許您以各種格式運行錦標賽。現在我遇到的問題是我需要爲每種不同錦標賽格式使用相同的路線。每種格式都有非常不同的邏輯和視圖。Laravel應用程序結構/體系結構

起初我只具有單一TournamentController和if語句中的每個函數用於檢查的類型,並執行適當的邏輯,例如:

public function start($tournamentId){ 

    $tournament = Tournament::find($tournamentId); 

    if($tournament->type == "single elimination"){ 

     //single elimination logic 

    }elseif($tournament->type == "round robin"){ 

     //round robin logic 

    } 

} 

現在我知道我添加更多比賽類型中,具有這種TournamentController中每個函數的邏輯類型都會變得混亂。於是我創建了兩個獨立的控制器,SingleEliminationController和RoundRobinController,並在路線文件我做類似的東西製作成動態控制器:

$tournament = Tournament::find(Request::segment(2)); 

    $controller = str_replace(' ', '', $tournament->tournamentType()); 

Route::get('{tournamentId}/{slug}', $controller . '[email protected]')->where('tournamentId', '[0-9]+'); 

這似乎更容易管理了一點,但它似乎仍然有點哈克,我肯定有一個更好的方法來構建事物,但我無法弄清楚。任何幫助將不勝感激,謝謝!

+1

值得注意的是:http://www.objectmentor.com/resources/ articles/Clean_Code_Args.pdf – cwallenpoole 2014-11-14 19:46:23

+0

@cwallenpoole,well .. OP甚至沒有看到使用全局範圍的問題。我懷疑你的鏈接材料會有任何影響。 – 2014-11-16 22:41:33

+0

@tereško請隨時發佈更多有用的評論 – RMK147 2014-11-17 23:32:47

回答

0

試試這個:

Route::get('{tournamentId}/{tournamentType}', function($tournamentId, $tournamentType){ 
    $controllerName = studly_case($tournamentType).'Controller'; 
    return App::make($controllerName)->showTournament($tournamentId); 
})->where(array(
    'tournamentId' => '[0-9]+', 
    'tournamentType' => '(single elimination|round robin)' 
)); 

添加每tournamentType到WHERE條件,因此,如果輸入了類型不存在,路線不會被跳過。

順便說一句:我建議你改變你的比賽類型沒有空間,因爲他們可能在網址有問題。例如single-elimination

編輯

如果你有控制的過濾器,或者想要做一點更 「乾淨」

return App::make($controllerName)->callAction('showTournament', array($tournamentId)); 
+1

請注意,這會打破控制器級別之前/之後的過濾器。 – ceejayoz 2014-11-14 19:45:43

+0

@ceejayoz這是真的。我添加了一個應該保持控制器過濾器工作的替代方案 – lukasgeiter 2014-11-14 19:47:56

+0

感謝您的答案,這提供了什麼好處,我對atm做的方式,因爲還有很多其他的路線,我需要這樣做。 – RMK147 2014-11-15 13:50:11